Weird result of Java Integer left shift

前端 未结 2 760
慢半拍i
慢半拍i 2020-11-30 12:35

I\'m a little confused now by java left shift operation,

1<<31 =  0x80000000  --> this I can understand

But

1<         


        
2条回答
  •  庸人自扰
    2020-11-30 13:20

    As per the Java Language Specification 15.19. Shift Operators (slightly paraphrased):

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

    That means that (for example) 33, being the 6-bit binary 100001, is reduced to the 5-bit 00001 before being used. So x << 33 is identical to x << 1.

提交回复
热议问题