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

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

    // Purpose: to reverse bits in an unsigned short integer 
    // Input: an unsigned short integer whose bits are to be reversed
    // Output: an unsigned short integer with the reversed bits of the input one
    unsigned short ReverseBits( unsigned short a )
    {
         // declare and initialize number of bits in the unsigned short integer
         const char num_bits = sizeof(a) * CHAR_BIT;
    
         // declare and initialize bitset representation of integer a
         bitset bitset_a(a);          
    
         // declare and initialize bitset representation of integer b (0000000000000000)
         bitset bitset_b(0);                  
    
         // declare and initialize bitset representation of mask (0000000000000001)
         bitset mask(1);          
    
         for ( char i = 0; i < num_bits; ++i )
         {
              bitset_b = (bitset_b << 1) | bitset_a & mask;
              bitset_a >>= 1;
         }
    
         return (unsigned short) bitset_b.to_ulong();
    }
    
    void PrintBits( unsigned short a )
    {
         // declare and initialize bitset representation of a
         bitset bitset(a);
    
         // print out bits
         cout << bitset << endl;
    }
    
    
    // Testing the functionality of the code
    
    int main ()
    {
         unsigned short a = 17, b;
    
         cout << "Original: "; 
         PrintBits(a);
    
         b = ReverseBits( a );
    
         cout << "Reversed: ";
         PrintBits(b);
    }
    
    // Output:
    Original: 0000000000010001
    Reversed: 1000100000000000
    

提交回复
热议问题