bitwise rotation in c#

  • Thread starter Thread starter Ramtin Kazemi
  • Start date Start date
DeveloperX said:
int x = 1;
x<<=3;
Console.WriteLine(x.ToString()); //writes 8

Taking the question literally, that's not bitwise rotation, it's bitwise
shifting. The difference is what happens when you start shifting bits
off of one end, with shifting you lose them, with rotation they come
back in on the other end.

There is no built-in bitwise rotation operator in .NET that I'm aware
of, perhaps in 3.5 there could be something somewhere that I don't know
of, but in 2.0 I'm suspecting you have to roll your own.
 
DeveloperX said:
int x = 1;
x<<=3;
Console.WriteLine(x.ToString()); //writes 8

Beware! Shift is not the same as rotate. When rotating, the MSBit is moved
to the LSBit position whereas in a shift opration, the LSBit is set to 0.

To illustrate using a 4-bit variable with the initial bitpattern 1100:

Value after shift: 1000

Value after rotate: 1001

A solution might look something like:

int Rotate( int x )
{
if( 0x80000000 & x )
return (x << 1) | 0x00000001;
else
return x << 1;
}

I haven't used C# for some time so this may be a bit "C++'ish" :-)

Ebbe
 
Hi
How can i perform bitwise rotation in C#?

Hi Ramtin,
You'll probably need to add some error checking & input validation,
but something like this seems to work:

int rotateBits = 3;
int dataSize = 16;
bool rotateleft = true; // false = right

uint value = 0xABCD;
uint mask = (uint)((1 << dataSize) - 1);
if (rotateleft)
value = ((value << rotateBits) | (value >> (dataSize - rotateBits)))
& mask;
else
value = ((value >> rotateBits) | (value << (dataSize - rotateBits)))
& mask;

John
 
Hi
How can i perform bitwise rotation in C#?

This is one use case that should be implemented as a native BCL method
so that the JIT compiler could map it directly to a CPU instruction.
Another one I've been wanting is a function that counts the number set
bits in field.
 
Hi Ramtin,
You'll probably need to add some error checking & input validation,
but something like this seems to work:

int rotateBits = 3;
int dataSize = 16;
bool rotateleft = true; // false = right

uint value = 0xABCD;
uint mask = (uint)((1 << dataSize) - 1);
if (rotateleft)
value = ((value << rotateBits) | (value >> (dataSize - rotateBits)))
& mask;
else
value = ((value >> rotateBits) | (value << (dataSize - rotateBits)))
& mask;

John

Ah yes I spotted my error as soon as I hit post. I just popped back
with a proper solution but you all beat me too it :)
 
Back
Top