I am wondering how to implement a circular right shift by k of the bitstring represented by the int bits.
public int r
This should do it:
/**
* Rotate v right with k steps
*/
public static int rro(int v, int k) {
return (v >>> (k%32)) | (v << ((k%32)-32)
}
/**
* Rotate v left with k steps
*/
public static int lro(int v, int k) {
return (v << (k%32)) | (v >>> ((k%32)-32)
}
I think the other answers are wrong, since if you shift more than 32 positions, their algorithms fail. If you want bigger datatypes, you need to adjust the datatypes and the '32' in all places.