| Author |
Why is Integer.rotateLeft() implemented in this way?
|
Leon Omk
Ranch Hand
Joined: Aug 17, 2010
Posts: 72
|
|
Isn't (i >>> distance) enough? Why (i >>> distance) | (i << -distance)?
|
OK, so that other guy knows Java better than I do, but I bet he can't speak Wuhanese(a Chinese Dialect) like me.
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19230
|
|
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.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
 |
|
|
subject: Why is Integer.rotateLeft() implemented in this way?
|
|
|