Java - Circular shift using bitwise operations

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

提交回复
热议问题