I have this simple bit of code (pardon the pun) where i want to reverse the bits in the integers but only up to the most significant - not including the padding.
The goal is to have this kinda result:
0 => 0
1 => 1
10 => 01
1011 => 1101
111011 => 110111
I am not looking for total byte reversal like this:
0000 00001 => 1000 0000
So the goal is only reversal up to the most significant bit.
Here is my test code:
InitBitReversedIndices(6,Mathf.CeilToInt( Mathf.Log(6,2) ));
for (int i = 0; i < 6; i++)
Debug.Log(Convert.ToString(i, 2) + " => " + Convert.ToString(_reverseInts[i], 2));
The functions:
private uint BitReverse(uint x,int numBits)
{
uint y = 0;
for (uint i = 0; i < numBits; i++)
{
y <<= 1;
y |= x & 0x0001;
x >>= 1;
}
return y;
}
private void InitBitReversedIndices(int total, int log2N)
{
_reverseInts = new int[total];
int bits = log2N;
for (int i = 0; i < total; i++)
{
_reverseInts[i] = (int)BitReverse((uint)i, bits);
}
}
Data results:
0 => 0 //correct
1 => 10 //should be 1
10 => 1 //correct
11 => 11 //correct
100 => 0 // should be 1
101 => 10 // should be 101
Where have i gone wrong?