# Java program to reverse bits of a positive integer number

Java 8Object Oriented ProgrammingProgramming

#### Complete Java Programming Fundamentals With Sample Projects

98 Lectures 7.5 hours

#### Get your Java dream job! Beginners interview preparation

85 Lectures 6 hours

#### Core Java bootcamp program with Hands on practice

Featured

99 Lectures 17 hours

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 14:47:41