unsigned right Shift '>>>' Operator in Java [duplicate]

这一生的挚爱 提交于 2019-11-26 10:58:33

问题


Possible Duplicate:
Why is (-1 >>> 32) = -1?

The unsigned right shift operator inserts a 0 in the leftmost. So when I do

System.out.println(Integer.toBinaryString(-1>>>30))

output

11

Hence, it is inserting 0 in the left most bit.

System.out.println(Integer.toBinaryString(-1>>>32))

output

11111111111111111111111111111111

Shouldn\'t it be 0?


回答1:


See http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.19

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.

that is -1 >>> 32 is equivalent to -1 >>> 0 and -1 >>> 33 is equivalent to -1 >>> 1 and, especially confusing, -1 >>> -1 is equivalent to -1 >>> 31



来源:https://stackoverflow.com/questions/14501233/unsigned-right-shift-operator-in-java

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