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
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.