C# bitwise rotate left and rotate right

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

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

6条回答
  •  不思量自难忘°
    2020-12-09 02:02

    There's no built-in language feature for bit rotation in C#, but these extension methods should do the job:

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

    Note: As Mehrdad points out, right-shift (>>) for signed integers is a peculiarity: it fills the MSBs with sign bit rather than 0 as it does for unsigned numbers. I've now changed the methods to take and return uint (unsigned 32-bit integer) instead - this is also in greater accordance with the C++ rotl and rotr functions. If you want to rotate integers, just case them before passing, and again cast the return value, of course.

    Example usage:

    int foo1 = 8.RotateRight(3); // foo1 = 1
    int foo2 = int.MinValue.RotateLeft(3); // foo2 = 4
    

    (Note that int.MinValue is 111111111111111111111111 - 32 1s in binary.)

提交回复
热议问题