Java - Circular shift using bitwise operations

后端 未结 5 1783
我寻月下人不归
我寻月下人不归 2020-12-05 00:58

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

public int r         


        
相关标签:
5条回答
  • 2020-12-05 01:12

    This should work:

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

    Also see the Wikipedia article on circular shifts.

    0 讨论(0)
  • 2020-12-05 01:16

    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.

    0 讨论(0)
  • 2020-12-05 01:22

    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.

    0 讨论(0)
  • 2020-12-05 01:28

    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
    
    0 讨论(0)
  • 2020-12-05 01:33
    int x=12345,n=5;
    System.out.println((x%10)*Math.pow(10, n-1)+(x/10));
    

    To shift by one bit .

    0 讨论(0)
提交回复
热议问题