Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# Why is Integer.rotateLeft() implemented in this way?

Leon Omk
Ranch Hand
Posts: 75

Isn't (i >>> distance) enough? Why (i >>> distance) | (i << -distance)?

Rob Spoor
Sheriff
Posts: 20709
68
i >>> distance shifts all bits to the right, and uses zeros to fill the gaps on the left. But that's not what the method should do; it should take the bits that were cut off by the shifting, and use those to fill the gaps. That's what i << -distance is for. The result is then joined using the |.

An example:
rotateRight(481, 5)

481 is 0000 0000 0000 0000 0000 0001 1110 0001

481 >>> 5 cuts off the last 5 bits, and adds 5 zeros at the start:
0000 0000 0000 0000 0000 0000 0000 1111 (15)

481 << -5 is the same as 481 << 27, so it cuts off 27 leading bits and adds 27 zeros at the end:
0000 1000 0000 0000 0000 0000 0000 0000 (134217728)

Now if you'd join those with | you get the following:
0000 1000 0000 0000 0000 0000 0000 1111 (134217743)

In other words, the last 5 bits are taken from the right and added to the left.