简体   繁体   中英

Bit Reversal: Generating Bit Reversal Lookup Table for N-Bits

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.

For 12-bit table:

int table[1<<12]; // or 4096
int i;

for (i=0;i<4096;i++) table[i] = my_straight_forward_bitreverse(12,i);

Then you have to solve the issue for other bit lengths.
Either have an array int table[12][4096]; which is about 90% unoccupied.

Or have

int table12[4096], table11[2048], table10[1024] /* , ...*/ ;  
int *table[12]={ table1, table2, /*  ...  */ table12 };

int i, j;
for (j=0;j<12;j++) 
  for (i=0;i<1<<j;i++) table[j][i]=my_straight_forward_bitreverse(j+1,i); 
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char **argv)
{
  const int bitSize = atoi(argv[1]);

  printf("static unsigned int table[] = {");
  unsigned int i;
  for (i = 0; i < 1 << bitSize; i++) {
    if ((i & 7) == 0)
      printf("\n");
    unsigned int v = i;
    unsigned int r = 0;
    int s = bitSize;
    while (s--) {
      r <<= 1;
      r |= v & 1;
      v >>= 1;
    }
    printf(" 0x%x,", r);
  }
  printf("\n};\n"
         "unsigned int lookup(int num, int bitSize)\n"
         "{\n"
         "        return table[num] >> (%d - bitSize);\n"
         "}\n",
         bitSize
         );

  return 0;
}

edit: implement j_random_hacker memory optimisation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM