我在java中使用右移运算符时遇到了一个奇怪的情况。当我右移 16 乘 31 时,结果为 0,但是尝试右移 16 乘 32 时,它本身仍然是 16。有人可以解释一下吗,因为我对此感到疯狂。
public class RightShiftTest {
public static void main(String args[]) {
int b = 16;
System.out.println("Bit pattern for int " + b + " is " +Integer.toBinaryString(b));
// As expected it is 0
System.out.println("After right-shifting " + b + " for 31 times the value is " + (b>>31) + " and bit pattern is " +Integer.toBinaryString(b>>31));
// But why is it not 0 but 16
System.out.println("After right-shifting " + b + " for 32 times the value is " + (b>>32) + " and bit pattern is " +Integer.toBinaryString(b>>32));
}
}
Output:
Bit pattern for int 16 is 10000
After right-shifting 16 for 31 times the value is 0 and bit pattern is 0
After right-shifting 16 for 32 times the value is 16 and bit pattern is 10000
The Java语言规范 http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.19 states
如果左侧操作数的提升类型是int
, 只有五个
右侧操作数的最低位用作移位
距离。就好像右边的操作数受到了
按位逻辑与运算符&
(§15.22.1) 与掩码值0x1f
(0b11111
)。实际使用的移动距离因此始终处于
范围 0 到 31(含)。
值 32 表示为
100000
最低 5 位是00000
so 0
,移位 0 位。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)