Bitwise rotation

FreewareFire

Freshman
Joined
May 23, 2003
Messages
28
Hi together!

I've searched for a class which rotates a value bitwise! By using only the << or >> Operator, the value will lost bits, because they filled with 0 ! Did someone know how i rotate a value without losing the bits? The value is 32 bits, unsigned!

This is an example for C++, but i can't get it work right for C#...

unsigned char ror(unsigned char val)
{
int highbit;
if(val & 0x80) // 0x80 is the high bit only
highbit = 1;
else
highbit = 0;
// Left shift (bottom bit becomes 0):
val >>= 1;
// Rotate the high bit onto the bottom:
val |= highbit;
return val;
}

Thank you! :D
 
Your method is called ror(), which I presume stands for "rotate right", but your code shifts left -- although the highbit part looks good for a right-shift method. It's a little confused... ;) I had a quick go, and came up with this pair:

[CS]
class Rotate
{
public static byte RotateLeft(byte val)
{
byte lowbit = (byte) ((val & 0x80) != 0 ? 0x1 : 0x0);
val <<= 1;
val |= lowbit;
return val;
}

public static byte RotateRight(byte val)
{
byte highbit = (byte) ((val & 0x1) != 0 ? 0x80 : 0x0);
val >>= 1;
val |= highbit;
return val;
}
}
[/CS]
 
Back
Top