java中的一个字节是8位长。 &
运算符执行按位and
运算。
十六进制表示需要两个十六进制字符0-F
。
0xFF
是一个字节。
如果我考虑 &
操作,我认为处理器会执行以下操作:
Bit no: 1 2 3 4 5 6 7 8 Binary: 0 0 0 0 0 0 1 0 = decimal 2 Operation: & & & & & & & & Value: 1 1 1 1 1 1 1 1 = 0xFF ---------------------------------------- Result: 0 0 0 0 0 0 1 0 = decimal 2
Because all binaries remain unchanged, it leads me to think that we do not need the & 0xFF
.
Code
public static void main(String[] args) {
byte b = -1;
System.out.println(String.valueOf(b).concat(" and ").concat(String.valueOf(b & 0xFF)));
}
结果
-1 and 255
如果我的假设(我们不需要 & 0xFF
)是正确的,为什么会有差异?
最佳答案
0xFF
等于值为 255
或 00000000 00000000 00000000 11111111
的 int。字节 -1 是 11111111
,并且因为它是有符号的,所以它被解释为 -1
。如果未签名,则也为 255
。
当你&
这两个值时,Java会以这两个值中较大者的类型返回结果,即int
,所以最终结果是一个int 位 00000000 00000000 00000000 11111111
,其计算结果为 255
。
关于java - 为什么按位与给出不同的字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50973482/