Java 有 2 个用于右移的移位运算符:
>> shifts right, and is dependant on the sign bit for the sign of the result
>>> shifts right and shifts a zero into leftmost bits
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/op3.html
这看起来相当简单,所以任何人都可以向我解释为什么当给 bar 的值为 -128 时,这段代码会为 foo 生成 -2 的值:
byte foo = (byte)((bar & ((byte)-64)) >>> 6);
这样做的目的是取一个 8 位字节,掩码最左边的 2 位,并将它们移到最右边的 2 位。IE:
initial = 0b10000000 (-128)
-64 = 0b11000000
initial & -64 = 0b10000000
0b10000000 >>> 6 = 0b00000010
结果实际上是-2,即
0b11111110
IE。1s 而不是 0s 被移到左边的位置