1

I came through an interview question. Reverse bits of a 32 bit unsigned integer. I wrote this code which is completely okay:

uint32_t reverseBits(uint32_t n) {
    for(int i = 0, j = 31; i < j; i++, j--) {
        bool iSet = (bool)(n & (1 << i));
        bool jSet = (bool)(n & (1 << j));
        n &= ~(1 << j);
        n &= ~(1 << i);
        if(iSet) n |= (1 << j);
        if(jSet) n |= (1 << i);
    }
    return n;
}

After this, there was a follow up question - If this function is called many times, how would you optimize it? I can not figure out how the solution should be optimized in that scenario.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Kaidul
  • 15,409
  • 15
  • 81
  • 150
  • 6
    Obligatory link to [Bit Twiddling Hacks](https://graphics.stanford.edu/~seander/bithacks.html#BitReverseObvious). – zch Sep 25 '18 at 21:09
  • 1
    Working code that you think can be made better? This looks like a job for [Coooooooode Review!](https://codereview.stackexchange.com/help/asking) I've linked to the how to ask page because it's worth a read to make sure any posts you make meet their requirements. – user4581301 Sep 25 '18 at 21:19

1 Answers1

5

You can optimize the loop by using a reverse lookup table.
For more detailed information you can follow this URL from which I have taken below code.

// Generate a lookup table for 32bit operating system 
// using macro 
#define R2(n)     n,     n + 2*64,     n + 1*64,     n + 3*64
#define R4(n) R2(n), R2(n + 2*16), R2(n + 1*16), R2(n + 3*16)
#define R6(n) R4(n), R4(n + 2*4 ), R4(n + 1*4 ), R4(n + 3*4 )

// Lookup table that store the reverse of each table
unsigned int lookuptable[256] = { R6(0), R6(2), R6(1), R6(3) };

/* Function to reverse bits of num */
int reverseBits(unsigned int num)
{
    int reverse_num = 0;

     // Reverse and then rearrange 

                   // first chunk of 8 bits from right
     reverse_num = lookuptable[ num & 0xff ]<<24 | 

                   // second chunk of 8 bits from  right 
                   lookuptable[ (num >> 8) & 0xff ]<<16 | 

                   lookuptable[ (num >> 16 )& 0xff ]<< 8 |
                   lookuptable[ (num >>24 ) & 0xff ] ;

    return reverse_num;
}
Mayur
  • 2,583
  • 16
  • 28