This question already has answers here:
How do shift operators work in Java? [duplicate]

(9个答案)


5年前关闭。




我在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

最佳答案

Java Language Specification状态

如果左侧操作数的提升类型为int仅五个
右侧操作数的最低位用作移位
距离。
就像右手操作数受到了
具有掩码值&的按位逻辑AND运算符0x1f(第15.22.1节)
(0b11111)。因此,实际使用的移动距离始终在
范围从0到31(含)。


值32表示为

100000

最低的5位是00000,所以0移位了0位。

10-01 13:55
查看更多