Write an Efficient C Program to Reverse Bits of a Number in C++


In this problem, we are given an unsigned integer n. Our task is to create a program that returns the number which is generated by reversing all the bits of the number.

Let’s take an example to understand the problem,

Input

n = 1

Output

2147483648

Explanation

binary of 1 is 000...0001, the reverse is 100...0000.

To solve this problem, we simple solution will be using a simple formula. We will loop through the binary of the number. And find the position of the set bit in the number lets say it i. The result will be calculated using the formula, ((total_number_of_bits) - 1) - i

Program to show the implementation of this algorithm,

Example

 Live Demo

#include<iostream>
using namespace std;
unsigned int reverseBitNumber(unsigned int num) {
   unsigned int totalNumberOfBits = sizeof(num) * 8;
   unsigned int reverseNumber = 0, temp;
   for (int i = 0; i < totalNumberOfBits; i++){
      if((num & (1 << i)))
         reverseNumber |= (1 << ((totalNumberOfBits - 1) - i));
   }
   return reverseNumber;
}
int main() {
   unsigned int n = 21;
   cout<<"The number is "<<n<<endl;
   cout<<"The number which has reverse bits of the number is :"<<reverseBitNumber(n);
   return 0;
}

Output

The number is 2
The number which has reverse bits of the number is :2818572288

Method 2

Another method is using shifting, we will shift the bits of the number until it become zero and the shift them in reverse number and then shift the bits remaining number of times to get the result.

Program to show the implementation of our solution,

Example

 Live Demo

#include<iostream>
using namespace std;
unsigned int reverseBitNumber(unsigned int n){
   unsigned int rem_shift = sizeof(n) * 8 - 1;
   unsigned int reverseNubmer = n;
   n >>= 1;
   while(n){
      reverseNubmer <<= 1;
      reverseNubmer |= n & 1;
      n >>= 1;
      rem_shift--;
   }
   reverseNubmer <<= rem_shift;
   return reverseNubmer;
}
int main(){
   unsigned int n = 21;
   cout<<"The number is "<<n<<endl;
   cout<<"The number which has reverse bits of the number is :"<<reverseBitNumber(n);
   return 0;
}

Output

The number is 21
The number which has reverse bits of the number is :2818572288

Updated on: 17-Apr-2020

754 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements