Hi
I am looking for C# equivalent (.Net 2) of _rotl and _rotr from c++.
Any ideas ?
Thanks,
Hi
I am looking for C# equivalent (.Net 2) of _rotl and _rotr from c++.
Any ideas ?
Thanks,
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 RotateLeft(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.)
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.
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)));
}