advertisement
Login | Register   
  Include Code  Search Tips
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   TIP BANK
Browse DevX
Partners & Affiliates
advertisement
advertisement
Tip of the Day
Expertise: Beginner
Language:
April 28, 2000
Bit Rotation for Byte, Short and Int Variables
This is a Class to perform rotr and rotl as known in standard C implementations and a rotate with carry implementation. The technique used is to determine which bits within the variable will be affected and then calculate where those bits will wind up after the rotate. To do this we must determine the bits which will be impacted on the rotate, so we calculate a mask to use to save off the bits which will be rotated. Then we perform the rotation, then we "add" the bits back in the location where they would have been had java had a rot(l|r) with carry.

public final class Rotate {
public static final int ROTATE_LEFT = 1;
public static final int ROTATE_RIGHT = 2;
Calculate the mask to use to mask off the bits which will be rotated out of the variable. For example, if we are going to rotr 4 bits, the right most 4 bits will be rotated out of the variable, so the mask should be: 0x0000000F. Or, if we rotl 8 bits, then the mask should be 0xFF000000.

* @param bitstorotate number of bits to rotate
* @param direction which direction to rotate ROTATE_LEFT or ROTATE_RIGHT
* @return the mask for masking out the bits which will be displaced in the rotate
*/
private static int calcmask(int bitstorotate, int direction)
{
int mask = 0;
int c;
if (bitstorotate == 0)
return 0;
c = 0x80000000;
mask = (c >> bitstorotate);
if (direction == ROTATE_RIGHT)
{
mask = (c >> (32 - bitstorotate));
mask = ~mask;
}
else
mask = (c >> bitstorotate);
return mask;
}

It's quick, easy and you get access to all the articles on DevX.
This registration/login is to allow you to read articles on devx.com.
Already a member?





Jeff Boyle
If you have a hot tip and we publish it, we'll pay you. However, due to accounting overhead we no longer pay $10 for a single tip submission. You must accumulate 10 acceptable tips to receive payment. Be sure to include a clear explanation of what the technique does and why it's useful. If it includes code, limit it to 20 lines if possible. Submit your tip here.
advertisement
advertisement