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

后端 未结 26 1384
情深已故
情深已故 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条回答
  •  -上瘾入骨i
    2020-11-22 07:00

    It seems that many other posts are concerned about speed (i.e best = fastest). What about simplicity? Consider:

    char ReverseBits(char character) {
        char reversed_character = 0;
        for (int i = 0; i < 8; i++) {
            char ith_bit = (c >> i) & 1;
            reversed_character |= (ith_bit << (sizeof(char) - 1 - i));
        }
        return reversed_character;
    }
    

    and hope that clever compiler will optimise for you.

    If you want to reverse a longer list of bits (containing sizeof(char) * n bits), you can use this function to get:

    void ReverseNumber(char* number, int bit_count_in_number) {
        int bytes_occupied = bit_count_in_number / sizeof(char);      
    
        // first reverse bytes
        for (int i = 0; i <= (bytes_occupied / 2); i++) {
            swap(long_number[i], long_number[n - i]);
        }
    
        // then reverse bits of each individual byte
        for (int i = 0; i < bytes_occupied; i++) {
             long_number[i] = ReverseBits(long_number[i]);
        }
    }
    

    This would reverse [10000000, 10101010] into [01010101, 00000001].

提交回复
热议问题