C# bitwise rotate left and rotate right

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

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

6条回答
  •  爱一瞬间的悲伤
    2020-12-09 01:57

    Note that if you want to create overloads that operate on shorter integral values, you need to add an extra step, as shown in:

    public static byte RotateLeft(
        this byte value,
        int count )
    {
        // Unlike the RotateLeft( uint, int ) and RotateLeft( ulong, int ) 
        // overloads, we need to mask out the required bits of count 
        // manually, as the shift operaters will promote a byte to uint, 
        // and will not mask out the correct number of count bits.
        count &= 0x07;
        return (byte)((value << count) | (value >> (8 - count)));
    }
    

    The masking operation is not needed for the 32-bit and 64-bit overloads, as the shift operators themselves take care of it for those sizes of left-hand operands.

提交回复
热议问题