Is java bit shifting circular?

前端 未结 2 529
终归单人心
终归单人心 2020-12-11 06:14

I have this behavior using Java:

int b=16;
System.out.println(b<<30);
System.out.println(b<<31);
System.out.println(b<<32);
System.out.prin         


        
2条回答
  •  感情败类
    2020-12-11 06:43

    No, it's not circular shift. It's normal left-shift. It's just that, for int type left side operand, Java uses just 5 lower order bits of the right operand for shifting. This is as per JLS §15.9:

    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

    So, for 16 << 32, considering only 5 lower order bits of 32, the expression is equivalent to:

    16 << 32 & 0x1f
    

    which is equal to 16.

提交回复
热议问题