I’m trying to do a bit reversal, I understand the straight forward implementation, but for performance purposes I need to reverse bits by building a lookup table and using that table to find the bit reversals, So my program will build a look up table for bitsize N, and then it will use the table to find the bit reversal for given bits.
for example, if bitSize = 9 and num = 6 (00000110)
reverse(num,bitSize) will return 192 which is 11000000
int lookup(int num, int bitSize)
{
return table[bitSize][num]; // == reverse(num,bitSize);
}
I think this is how the lookup function should look like, I’ve been told that it’s possible to build the table but I don’t have any idea how to, can someone explain how to build this table?
I just want to clarify that I’m looking for a way to build this table for given bitSize, not just for 32-bit, otherwise I would have used this method:
http://graphics.stanford.edu/~seander/bithacks.html#BitReverseTable
Thank you for your help,
Edit:
Both solutions work but kmkaplan’s solution is more efficient, thanks to j_random_hacker’s memory optimisation.
edit: implement j_random_hacker memory optimisation.