# Reverse bits in java

In this tutorial, we learn how to reverse bits in Java without using any inbuilt functions.

Given a number, reverse the bits in the binary representation (consider 32-bit unsigned data) of the number, and print the new number formed.

**Input Format**

First line of input contains T – number of test cases. Each of the next T lines contains N. ( a number integer )

**Constraints**

1 <= T <= 100000

0 <= N <= 10^9

**Output Format**

For each test case, print the new number formed after reversing the bits, separated by new line.

**Sample Input**

4

4

15

6

1000000000

**Sample Output**

536870912

4026531840

1610612736

5462492

**Explanation**

**Test Case 1**

Binary Representation of 4: 000…100

After reversing the bits: 001…000 (536870912)

**Test Case 2**

Binary Representation of 15: 000…1111

After reversing the bits: 1111…000 (4026531840)

To solve this program since the boundary conditions show that the output may be more than 10^9 we choose long datatype to generate exact output. Firstly check which bits are set(possessing 1 in binary representation) in the given number. We have to place this bit exactly at the same position from the other end. So, we main pos variable to know the position and check whether bit is set or not by doing bitwise AND operation. Taking a variable j do bitwise left shift for 31 positions from other end(j<<(31 – pos)). Take a new variable ‘m’ initialize it to zero and perform XOR operation with j so as to avoid manipulating the ‘m’ variable. Then left shift the given number by 1 and increment pos.

import java.io.*; import java.util.*; import java.lang.*; public class codespeedy { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=1; while(t-- > 0) { long n=4; long i=1,pos=0,x=1; long m=0; while(i<=(x<<31)) { long j=1; if((n&i)==i) { m=m^(j<<(31-pos)); } i<<=1; pos++; } } System.out.println(m); } }

OUTPUT:

536870912

We hope this tutorial helped you to solve how to reverse bits.

Also read:

## Leave a Reply