- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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

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);

- Related Questions & Answers
- Python program to reverse bits of a positive integer number?
- Reverse actual bits of the given number in Java
- JavaScript Reverse the order of the bits in a given integer
- Java Program to Reverse a Number
- Write an Efficient C Program to Reverse Bits of a Number in C++
- Program to express a positive integer number in words in C++
- Java Program to Count set bits in an integer
- Java program to count total bits in a number
- Reverse an Integer in Java
- C++ Program to Reverse a Number
- Reverse Bits in C++
- Java Program to get the reverse of an Integer array with Lambda Expressions
- Java program to print the reverse of the given number
- Java Program to Check Whether a Number is Positive or Negative
- Program to invert bits of a number Efficiently in C++

Advertisements