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

后端 未结 26 1586
情深已故
情深已故 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 06:51

    Generic

    C code. Using 1 byte input data num as example.

        unsigned char num = 0xaa;   // 1010 1010 (aa) -> 0101 0101 (55)
        int s = sizeof(num) * 8;    // get number of bits
        int i, x, y, p;
        int var = 0;                // make var data type to be equal or larger than num
    
        for (i = 0; i < (s / 2); i++) {
            // extract bit on the left, from MSB
            p = s - i - 1;
            x = num & (1 << p);
            x = x >> p;
            printf("x: %d\n", x);
    
            // extract bit on the right, from LSB
            y = num & (1 << i);
            y = y >> i;
            printf("y: %d\n", y);
    
            var = var | (x << i);       // apply x
            var = var | (y << p);       // apply y
        }
    
        printf("new: 0x%x\n", new);
    

提交回复
热议问题