Weird result of Java Integer left shift

大兔子大兔子 提交于 2019-11-27 15:13:18

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.

Vikram Aditya
System.out.println(Integer.toBinaryString(1 << 32)); 

Shifts binary 1(10) by 32 times to the left. Hence: 1 in decimal

System.out.println(Integer.toBinaryString(1 << 33)); 

Now, int is of 4 bytes,hence 32 bits. So when you do shift by 33, it's equivalent to shift by 1. Hence : 2 in decimal

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