Java right shift integer by 32 [duplicate]

徘徊边缘 提交于 2019-11-29 22:12:24

问题


This question already has an answer here:

  • Findbugs warning: Integer shift by 32 — what does it mean? 2 answers

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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/32648097/java-right-shift-integer-by-32

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!