What is the C# equivalent (.NET 2.0) of _rotl
and _rotr
from C++?
Is this what you are trying to do?
Jon Skeet answered this in another site
Basically what you want is
(for left)
(original << bits) | (original >> (32 - bits))
or
(for right)
(original >> bits) | (original << (32 - bits))
Also, as Mehrdad has already suggested, this only works for uint, which is the example that Jon gives as well.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With