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 work:
return (bits >>> k) | (bits << (Integer.SIZE - k));
Also see the Wikipedia article on circular shifts.
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.
The answer by schnaader is correct:
return (bits >>> k) | (bits << (32-k));
(bits >>> k)
right-shifts the value stored in bits
by k
bits and 'the third >
' ensures that the leftmost bit is a zero instead of the sign of the bits
(bits << (32-k))
left-shifts the value in bits
by k
-complement number of bitsNow, you have two temporary variables where the first (32-k) bits are stored on the rightmost bits of var (1), and the last k bits are stored on the leftmost bits of var (2). The bitwise or operation simply ORs these two temp vars together (note the use of >>>
instead of >>
) and you have the circular shift.
You mean you want the bits rotated off the right-hand side to appear on the left?
return Integer.rotateRight(bits, k);
Example:
int n = 0x55005500; // Binary 01010101000000000101010100000000
int k = 13;
System.err.printf("%08x%n", Integer.rotateRight(n, k));
output:
a802a802 // Binary 10101000000000101010100000000010
int x=12345,n=5;
System.out.println((x%10)*Math.pow(10, n-1)+(x/10));
To shift by one bit .