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

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

    Another loop-based solution that exits quickly when the number is low (in C++ for multiple types)

    template
    T reverse_bits(T in) {
        T bit = static_cast(1) << (sizeof(T) * 8 - 1);
        T out;
    
        for (out = 0; bit && in; bit >>= 1, in >>= 1) {
            if (in & 1) {
                out |= bit;
            }
        }
        return out;
    }
    

    or in C for an unsigned int

    unsigned int reverse_bits(unsigned int in) {
        unsigned int bit = 1u << (sizeof(T) * 8 - 1);
        unsigned int out;
    
        for (out = 0; bit && in; bit >>= 1, in >>= 1) {
            if (in & 1)
                out |= bit;
        }
        return out;
    }
    

提交回复
热议问题