为什么如果
int x = -1 // binary: 11111111111111111111111111111111
x = x >>> 31;
我们有 00000000000000000000000000000001
但是如果
int x = -1
x = x >>> 32;
我们有 11111111111111111111111111111111(又是 -1)
但不是 00000000000000000000000000000000 吗?
最佳答案
来自 Section 15.19 of JLS :
If the promoted type of the left-hand operand is int, only the five lowest-order bits of the right-hand operand are used as the shift distance. It is as if the right-hand operand were subjected to a bitwise logical AND operator
&
(§15.22.1) with the mask value0x1f (0b11111)
. The shift distance actually used is therefore always in the range0 to 31
, inclusive.
强调我的。所以:
x >>> n
相当于:
x >>> n & 0x1f // or x >>> n % 32
因此,x >>> 32
等同于 x >>> 32 & 0x1f
<==> x >>> 0
== x
。
因此经验法则是,每当您将数字移动 32
(int
是 32 位
),你会得到相同的值。
关于java 位操作 >>> 移位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14817639/