有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

为什么在Java中,将16右移32得到16而不是0?16> >32=16为什么?

在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

共 (1) 个答案

  1. # 1 楼答案

    {a1}州

    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 value 0x1f (0b11111). The shift distance actually used is therefore always in the range 0 to 31, inclusive.

    值32表示为

    100000
    

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