开发者

Java - Circular shift using bitwise operations

开发者 https://www.devze.com 2023-03-02 00:30 出处:网络
I am wondering how to implement a circular right shift by k of the bitstring represented by the int bits.

I am wondering how to implement a circular right shift by k of the bitstring represented by the int bits.

public int rtCircShift(int bits, int k)
{
    r开发者_如何学编程eturn bits >> k;
}

All this code does is return 0, how can I make it a 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


This should work:

 return (bits >>> k) | (bits << (Integer.SIZE - k));

Also see the Wikipedia article on circular shifts.


The answer by schnaader is correct:

return (bits >>> k) | (bits << (32-k));
  1. the first part (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
  2. the second part (bits << (32-k)) left-shifts the value in bits by k-complement number of bits

Now, 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.


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.


int x=12345,n=5;
System.out.println((x%10)*Math.pow(10, n-1)+(x/10));

To shift by one bit .

0

精彩评论

暂无评论...
验证码 换一张
取 消