Efficient Algorithm for Bit Reversal (from MSB->LSB to LSB->MSB) in C

后端 未结 26 1383
情深已故
情深已故 2020-11-22 06:08

What is the most efficient algorithm to achieve the following:

0010 0000 => 0000 0100

The conversion is from MSB->LSB to LSB->MSB. All bits

26条回答
  •  难免孤独
    2020-11-22 07:11

    My simple solution

    BitReverse(IN)
        OUT = 0x00;
        R = 1;      // Right mask   ...0000.0001
        L = 0;      // Left mask    1000.0000...
        L = ~0; 
        L = ~(i >> 1);
        int size = sizeof(IN) * 4;  // bit size
    
        while(size--){
            if(IN & L) OUT = OUT | R; // start from MSB  1000.xxxx
            if(IN & R) OUT = OUT | L; // start from LSB  xxxx.0001
            L = L >> 1;
            R = R << 1; 
        }
        return OUT;
    

提交回复
热议问题