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

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

    Efficient can mean throughput or latency.

    For throughout, see the answer by Anders Cedronius, it’s a good one.

    For lower latency, I would recommend this code:

    uint32_t reverseBits( uint32_t x )
    {
    #if defined(__arm__) || defined(__aarch64__)
        __asm__( "rbit %0, %1" : "=r" ( x ) : "r" ( x ) );
        return x;
    #endif
        // Flip pairwise
        x = ( ( x & 0x55555555 ) << 1 ) | ( ( x & 0xAAAAAAAA ) >> 1 );
        // Flip pairs
        x = ( ( x & 0x33333333 ) << 2 ) | ( ( x & 0xCCCCCCCC ) >> 2 );
        // Flip nibbles
        x = ( ( x & 0x0F0F0F0F ) << 4 ) | ( ( x & 0xF0F0F0F0 ) >> 4 );
    
        // Flip bytes. CPUs have an instruction for that, pretty fast one.
    #ifdef _MSC_VER
        return _byteswap_ulong( x );
    #elif defined(__INTEL_COMPILER)
        return (uint32_t)_bswap( (int)x );
    #else
        // Assuming gcc or clang
        return __builtin_bswap32( x );
    #endif
    }
    

    Compilers output: https://godbolt.org/z/5ehd89

提交回复
热议问题