> How to use lookup table to reverse bits?

How to use lookup table to reverse bits?

Posted at: 2014-12-18 
using lookup table like this

lookuptable[16] = { 0x0, 0x8, 0x4, 0xC,

0x2, 0xA, 0x6, 0xE, 0x1, 0x9, 0x5, 0xD, 0x3, 0xB,

0x7, 0xF };

Assuming 32-bit unsigned values to reverse

int hc;

unsigned invalue, temp, outvalue;

temp = invalue;

outvalue = 0;

for (hc=0; hc<8; ++hc)

{

.... outvalue = outvalue<<4 + lookuptable[temp&0x0F];

.... temp = temp >> 4;

}

Each iteration of that loop reverses 4 low order bits of temp, shifts them left into the outvalue variable, then shifts those bits out of the temp variable. I use a temp because I don't like destroying my input value.

Reversing very long bit strings (too long to fit in any integral data type) can build on this "reverse a word" routine by reversing the first and last words then swapping them, then repeating that with the 2nd word and the next to last word, and so on until you reach the middle of the array.

using lookup table like this

lookuptable[16] = { 0x0, 0x8, 0x4, 0xC,

0x2, 0xA, 0x6, 0xE, 0x1, 0x9, 0x5, 0xD, 0x3, 0xB,

0x7, 0xF };