java位操作>>>转移 [英] java Bit operations >>> shift
问题描述
为什么如果
int x = -1 // binary: 11111111111111111111111111111111
x = x >>> 31;
我们有00000000000000000000000000000001
we have 00000000000000000000000000000001
但是如果
int x = -1
x = x >>> 32;
我们有11111111111111111111111111111111(再次-1)
we have 11111111111111111111111111111111 (again -1)
但不是00000000000000000000000000000000?
but not 00000000000000000000000000000000 ?
推荐答案
来自 JLS第15.19节:
如果左侧操作数的提升类型为int,则只有右侧操作数的五个
最低位用作shift
距离。就好像右手操作数受到
按位逻辑AND运算符&
(§15.22.1),掩码值0x1f
。因此,实际使用的移动距离始终在
(0b11111)
范围内0到31
,包括在内。
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
。
So, x >>> 32
is equivalent to x >>> 32 & 0x1f
<==> x >>> 0
== x
.
所以经验法则是,每当你将数字移动 32
的倍数时( int
是 32位
),你得到相同的值。
So the Rule of Thumb is, whenever you shift a number by a multiple of 32
(int
is 32 bits
), you get back the same value.
这篇关于java位操作>>>转移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!