I\'ve come up with several manual ways of doing this, but i keep wondering if there is something built-in .NET that does this.
Basically, i want to reverse the bit o
Please see this comprehensive bit-twiddling hacks, namely you want 'Reverse the bits in a byte with 3 operations (64-bit multiply and modulus division)'
int lVal = 0x9D;
int lNewVal = (int)((((ulong)lVal * 0x0202020202UL) & 0x010884422010UL) % 1023);
System.Diagnostics.Debug.WriteLine(string.Format("{0:X2}", lNewVal));
When you run this you will find that the value gets reversed to 0xB9.
You can find bit twiddling algorithms in the fxtbook. Chapter 1.14 gives these bit swapping algorithms:
static uint bitSwap1(uint x) {
uint m = 0x55555555;
return ((x & m) << 1) | ((x & (~m)) >> 1);
}
static uint bitSwap2(uint x) {
uint m = 0x33333333;
return ((x & m) << 2) | ((x & (~m)) >> 2);
}
static uint bitSwap4(uint x) {
uint m = 0x0f0f0f0f;
return ((x & m) << 4) | ((x & (~m)) >> 4);
}
Which makes your byte value bit reversal:
public static byte swapBits(byte value) {
return (byte)(bitSwap4(bitSwap2(bitSwap1(value))));
}
The x86 JIT compiler doesn't do a great job optimizing this code. If speed matters then you could use it to initialize a byte[] to make it a fast lookup instead.
private UInt32 BitReverse(UInt32 value)
{
UInt32 left = (UInt32)1 << 31;
UInt32 right = 1;
UInt32 result = 0;
for (int i = 31; i >= 1; i -= 2)
{
result |= (value & left) >> i;
result |= (value & right) << i;
left >>= 1;
right <<= 1;
}
return result;
}
You can loop through bits and and get them in reverse order:
public static byte Reverse(this byte b)
{
int a = 0;
for (int i = 0; i < 8; i++)
if ((b & (1 << i)) != 0)
a |= 1 << (7- i);
return (byte)a;
}
Using @Chads link
byte b;
b = 0x9D;
b = (byte)((b * 0x0202020202 & 0x010884422010) % 1023);
Edit: Forgot the cast
10 years later. But I hope this helps someone. I did a reverse operation like this:
byte Reverse(byte value)
{
byte reverse = 0;
for (int bit = 0; bit < 8; bit++)
{
reverse <<= 1;
reverse |= (byte)(value & 1);
value >>= 1;
}
return reverse;
}