C++ Program Reverse Bits of a Number

Today we will learn how to reverse the bits of a number and display the value of the reversed number in C++ programming.

For this problem we will have to use concepts of bitwise manipulation such as left shift (>>), right shift (<<), and (&), or (|), etc.

First, we will input the unsigned integer number and run it through a loop, this loop will iterate 32 times as the integer number is represented by 32 bits.

  • a>>i obtains the ith bit from the input integer by the virtue of the left-shift operation
  • (a>>i)&1 will AND the obtained bit with 1, hence giving us the output as the bit itself
  • now we need to store this bit at the (32-i-1)th position in the reversed number
  • and finally, every time the loop executes, we OR it with the previous value of the reversed number so that we sustain the bits obtained in each step and form the complete number.

Below is our C++ program for reverse bits of a number:

#include <iostream>
#include <string.h>
#include <stdlib.h>
using namespace std;
int main(int argc, const char * argv[]) {
    unsigned int n;
    unsigned int revnum=0;
    cout<<"Enter an unsigned int ";
    for(int i=0;i<32;i++)
        revnum|= ((n >> i)&1) << (32-i-1);  //main and only logic required 
    cout<<"Original Number is "<<n<<endl;
    cout<<"Reversed Number is "<<revnum<<endl;
    cout<<"Binary representation of reversed number: \n";
    unsigned j;
    //this is a function to obtain binary representation of any integer number (Extra)
    for (j = 1 << 31; j > 0; j = j / 2)
        (revnum & j)? cout<<("1"): cout<<("0");
    return 0;

Now let’s see what would be the output of the program:

Enter an unsigned int 1
Original Number is 1
Reversed Number is 2147483648
Binary representation of reversed number: 

Leave a Reply

Your email address will not be published. Required fields are marked *