Is there a way to perform a circular bit shift in C#?

后端 未结 6 955
太阳男子
太阳男子 2020-11-29 04:58

I know that the following is true

int i = 17; //binary 10001
int j = i << 1; //decimal 34, binary 100010

But, if you shift too far, t

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-29 05:47

    Just as reference on how to do it, these two functions work perfectly for rotating the bits of 1/2word:

    static public uint ShiftRight(uint z_value, int z_shift)
    {
        return ((z_value >> z_shift) | (z_value << (16 - z_shift))) & 0x0000FFFF;
    }
    
    static public uint ShiftLeft(uint z_value, int z_shift)
    {
        return ((z_value << z_shift) | (z_value >> (16 - z_shift))) & 0x0000FFFF;
    }
    

    It would be easy to extend it for any given size.

提交回复
热议问题