What is the C# equivalent (.NET 2.0) of _rotl and _rotr from C++?
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)));
}