Java right shift integer by 32 [duplicate]

2020-02-29 06:41发布

I am trying to right shift an integer by 32 but the result is the same number. (e.g. 5 >> 32 is 5.)

If I try to do same operation on Byte and Short it works. For example, "(byte)5 >> 8" is 0.

What is wrong with Integer?

2条回答
成全新的幸福
2楼-- · 2020-02-29 07:36

A Shifting conversion returns result as an int or long. So, even if you shift a byte, you will get an int back.

Java code :

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

Byte code :

         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
查看更多
Bombasti
3楼-- · 2020-02-29 07:37

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.

so shifting 32 is not effective.

查看更多
登录 后发表回答