C# bitwise rotate left and rotate right

后端 未结 6 1948
不思量自难忘°
不思量自难忘° 2020-12-09 01:42

What is the C# equivalent (.NET 2.0) of _rotl and _rotr from C++?

6条回答
  •  一个人的身影
    2020-12-09 01:58

    The naive version of shifting won't work. The reason is, right shifting signed numbers will fill the left bits with sign bit, not 0:

    You can verify this fact with:

    Console.WriteLine(-1 >> 1);
    

    The correct way is:

    public static int RotateLeft(this int value, int count)
    {
        uint val = (uint)value;
        return (int)((val << count) | (val >> (32 - count)));
    }
    
    public static int RotateRight(this int value, int count)
    {
        uint val = (uint)value;
        return (int)((value >> count) | (value << (32 - count)));
    }
    

提交回复
热议问题