Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Leon Omk
Ranch Hand
Posts: 75
Chrome Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Isn't (i >>> distance) enough? Why (i >>> distance) | (i << -distance)?
 
Rob Spoor
Sheriff
Pie
Posts: 20533
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic