0

Why the expression (-1 >>> 32) in Java is evaluated to -1 instead of 0 as expected? The >>>-shift-operator should fill in preceeding 0s, so the result should have all bits set to 0.

This is weird, because it breaks the semantics of >>>: e.g. (-1 >>> x) has the first x bits set to 0 for all 0 <= x <= 31. The only (unexpected) exception is 32.

Is this intentional behaviour, a bug or an (overmotivated) compiler optimization?

I used the expression ~(-1 >>> x) for expanding a cidr-netmask to its 32-bit equivalent, but as it seems, /32-masks have to be handled separately.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199

1 Answers1

1

Check this post.

Quote from answer author Rasmus Faber

From the Java Language Specification:

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. The shift distance actually used is therefore always in the range 0 to 31, inclusive.

Long in short: due to operand range limit, -1 >>> 32 is equivalent to -1 >>> 0 which is -1.

Community
  • 1
  • 1
Zodiase
  • 13
  • 3