Java program to reverse bits of a positive integer number


The bits of an integer number can be reversed to obtain another number. An example of this is given as follows −

Number = 11
Binary representation = 1011
Reversed binary representation = 1101
Reversed number = 13

A program that demonstrates this is given as follows −

Example

 Live Demo

public class Example {
   public static void main(String[] args) {
      int num = 14;
      int n = num;
      int rev = 0;
      while (num > 0) {
         rev <<= 1;
         if ((int)(num & 1) == 1)
         rev ^= 1;
         num >>= 1;
      }
      System.out.println("The original number is: " + n);
      System.out.println("The number with reversed bits is: " + rev);
   }
}

Output

The original number is: 14
The number with reversed bits is: 7

Now let us understand the above program.

The number is defined. Then a while loop is used to reverse the bits of the number. The code snippet that demonstrates this is given as follows −

int num = 14;
int n = num;
int rev = 0;
while (num > 0) {
   rev <<= 1;
   if ((int)(num & 1) == 1)
   rev ^= 1;
   num >>= 1;
}

Finally, the number, as well as the reversed number, are displayed. The code snippet that demonstrates this is given as follows −

System.out.println("The original number is: " + n);
System.out.println("The number with reversed bits is: " + rev);

Updated on: 27-Jun-2020

214 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements