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

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

    You might want to use the standard template library. It might be slower than the above mentioned code. However, it seems to me clearer and easier to understand.

     #include
     #include
    
    
     template
     const std::bitset reverse(const std::bitset& ordered)
     {
          std::bitset reversed;
          for(size_t i = 0, j = N - 1; i < N; ++i, --j)
               reversed[j] = ordered[i];
          return reversed;
     };
    
    
     // test the function
     int main()
     {
          unsigned long num; 
          const size_t N = sizeof(num)*8;
    
          std::cin >> num;
          std::cout << std::showbase << std::hex;
          std::cout << "ordered  = " << num << std::endl;
          std::cout << "reversed = " << reverse(num).to_ulong()  << std::endl;
          std::cout << "double_reversed = " << reverse(reverse(num)).to_ulong() << std::endl;  
     }
    

提交回复
热议问题