跳转至

Java中字节byte与位操作

byte的一些基础

0b 开头,后面接上每一位

byte b1 = 0b1;
byte b2 = 0b10;
byte b3 = 0b11;
byte b4 = 0b100;

Integer.toBinaryString获得字符串形式

测试输入
byte b1 = 0b1;
byte b2 = 0b10;
byte b3 = 0b11;
byte b4 = 0b100;
System.out.println(Integer.toString(b1) + ", " +Integer.toBinaryString(b1));
System.out.println(Integer.toString(b2) + ", " +Integer.toBinaryString(b2));
System.out.println(Integer.toString(b3) + ", " +Integer.toBinaryString(b3));
System.out.println(Integer.toString(b4) + ", " +Integer.toBinaryString(b4));

输出
1, 1
2, 10
3, 11
4, 100

更多的位,如64,127

byte b1000000 = 0b1000000;
System.out.println(Integer.toString(b1000000) + ", " +Integer.toBinaryString(b1000000));
byte b127 = 0b1111111;
System.out.println(Integer.toString(b127) + ", " +Integer.toBinaryString(b127));
int b128 = 0b10000000;
System.out.println(Integer.toString(b128) + ", " +Integer.toBinaryString(b128));

输出
64, 1000000
127, 1111111
128, 10000000

Java中,byte最大是127(Byte.MAX_VALUE),最小是-128(Byte.MIN_VALUE)

System.out.println(Integer.toString(Byte.MIN_VALUE) + ", " +Integer.toBinaryString(Byte.MIN_VALUE));
// -128, 11111111111111111111111110000000

左移一位 <<

1
2
3
4
5
6
7
System.out.println("0x" + Integer.toBinaryString(1));
System.out.println("0x" + Integer.toBinaryString(2));
System.out.println("0x" + Integer.toBinaryString(3));
System.out.println("0x" + Integer.toBinaryString(1 << 1));
System.out.println("0x" + Integer.toBinaryString(1 << 2));
System.out.println("0x" + Integer.toBinaryString(1 << 3));
System.out.println("0x" + Integer.toBinaryString(1 << 4));
输出
0x1
0x10
0x11
0x10
0x100
0x1000
0x10000
本站说明

一起在知识的海洋里呛水吧。广告内容与本站无关。如果喜欢本站内容,欢迎投喂作者,谢谢支持服务器。如有疑问和建议,欢迎在下方评论~

📖AndroidTutorial 📚AndroidTutorial 🙋反馈问题 🔥最近更新 🍪投喂作者

Ads