Java - Circular shift using bitwise operations

后端 未结 5 1796
我寻月下人不归
我寻月下人不归 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: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.

提交回复
热议问题