Java 整数右移 32

Java right shift integer by 32

我试图将整数右移 32,但结果是相同的数字。 (例如 5 >> 32 是 5。)

如果我尝试对 Byte 和 Short 执行相同的操作,它会起作用。例如“(byte)5 >> 8”为0.

整数有什么问题?

JLS 15.19. Shift Operators

... 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.

所以移动 32 无效。

移位转换 returns 结果为 intlong。所以,即使你移动 byte,你也会得到 int

Java代码:

public static void main(String s[]) {
    byte b = 5;
    System.out.println(b >> 8);
    int i = 8;
    System.out.println(i >> 32);
}

字节码:

         0: iconst_5
         1: istore_1
         2: getstatic     #16                 // Field java/lang/System.out:Ljava/io/PrintStream; 
         5: iload_1
         6: bipush        8
         8: ishr
         9: invokevirtual #22      // Method java/io/PrintStream.println:(I)V  ==> Using println(int)
        12: bipush        8
        14: istore_2
        15: getstatic     #16     // Field java/lang/System.out:Ljava/io/PrintStream;
        18: iload_2
        19: bipush        32
        21: ishr
        22: invokevirtual #22      // Method java/io/PrintStream.println:(I)V   ==> Using println(int)
        25: return