0
votes

According to Section 15.19 of the JLS:

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.

If the promoted type of the left-hand operand is long, then only the six 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 0x3f (0b111111). The shift distance actually used is therefore always in the range 0 to 63, inclusive.

The same thing we can find in C#. In Python it will be 6 bits instead of 5, but the logic remains the same.

What the reasoning behind it? For me it would be more naturally to have the following:

x << 32 = 0 

instead of

x << 32 = x

Moreover we will never get 0 using shift operation for negative ints.

1
Aren't you talking about "shifting" vs "rotation"? - Federico klez Culloca

1 Answers

0
votes

From book "Java Puzzlers: Traps, Pitfalls and Corner Cases" by Joshua Bloch and Neal Gafter:

Language designers should perhaps consider restricting shift distances to the range from 0 to the type size in bits and changing the semantics of shifting a value by the type size to return 0. Although this would avoid the confusion …, it could have negative performance consequences; Java's semantics for the shift operators are those of the shift instructions on many processors.