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

后端 未结 26 1354
情深已故
情深已故 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:00

    I think the simplest method I know follows. MSB is input and LSB is 'reversed' output:

    unsigned char rev(char MSB) {
        unsigned char LSB=0;  // for output
        _FOR(i,0,8) {
            LSB= LSB << 1;
            if(MSB&1) LSB = LSB | 1;
            MSB= MSB >> 1;
        }
        return LSB;
    }
    
    //    It works by rotating bytes in opposite directions. 
    //    Just repeat for each byte.
    

提交回复
热议问题