wood burning stoves 2.0*
The moose likes Java in General and the fly likes Why is Integer.rotateLeft() implemented in this way? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Why is Integer.rotateLeft() implemented in this way?" Watch "Why is Integer.rotateLeft() implemented in this way?" New topic
Author

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

Leon Omk
Ranch Hand

Joined: Aug 17, 2010
Posts: 75



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: 19760
    
  20

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 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
wood burning stoves
 
subject: Why is Integer.rotateLeft() implemented in this way?