Is there a way to perform a circular bit shift in C#?
One year ago I've to implement MD4 for my undergraduate thesis. Here it is my implementation of circular bit shift using a UInt32.
private UInt32 RotateLeft(UInt32 x, Byte n)
{
return UInt32((x << n) | (x >> (32 - n)));
}
If you know the size of type, you could do something like:
uint i = 17;
uint j = i << 1 | i >> 31;
... which would perform a circular shift of a 32 bit value.
As a generalization to circular shift left n bits, on a b bit variable:
/*some unsigned numeric type*/ input = 17;
var result = input << n | input >> (b - n);
@The comment, it appears that C# does treat the high bit of signed values differently. I found some info on this here. I also changed the example to use a uint.