20

For example, I have the binary number 1011 which is equal to decimal 11. I want the reverse bit's location such that it become 1101, which is decimal 13. Here is code:

import java.util.*; public class bits { public static void main(String[] args) { Scanner scnr=new Scanner(System.in); System.out.println("enter x:"); int x=scnr.nextInt(); int b=0; while (x!=0){ b|=( x &1); x>>=1; b<<=1; } System.out.println(b); } } 

But when I enter x 11 then it prints 26. What is the mistake?

2
  • 3
    a full Integer can be reversed with Integer.reverse(int i) - but as it looks like you want to reverse integers with less bits, I leave it as a comment. Commented Jul 2, 2010 at 12:57
  • 1
    looks like the solution is already here: stackoverflow.com/questions/746171/… You are missing that there needs to be an extra shift needed at end Commented Jul 2, 2010 at 13:06

13 Answers 13

32

You are shifting b one time too many. Do the shift first (so that the first time, when b == 0, it has no effect):

while (x!=0){ b<<=1; b|=( x &1); x>>=1; } 
Sign up to request clarification or add additional context in comments.

4 Comments

What if we also want to consider the padding? 1011 is actually 00001011 so the reverse must be 10110000
Then you can use a for loop that does a fixed number of iterations.
You replied to a 11 year old thread! Damn! Also, yeah I did that! Thank you!! I maintained a count and then did b<<=(8-count)
Can't resist that red notification counter ;)
16

Slightly offtopic. There's also the option of the built-in bit reversing features of Java.

See http://java.sun.com/javase/6/docs/api/java/lang/Integer.html#reverse(int)

EDIT: This assumes you're using Java 1.5 or newer.

Comments

4
  1. Use >>>= instead of >>=
  2. If you want to change method signature to public static byte reverse(byte in) this will not work on negative values because there is implicit cast to int.

Comments

2

The program do not work for input like 1, 2

int reverseBits(int x) { int b = 0; while (x != 0) { b <<= 1; b |= ( x & 1); x >>= 1 } return b; } 

input 1 output 1, should be 8 right? input 2 output 1, should be 4.

Comments

2

Note for beginners: I use hexadecimal (0-9 and A-F) because one hexadecimal digit maps to 4 binary bits perfectly. Instead of writing 1010, I use A (10 decimal). You can tell Java to use hexadecimal (literals) by starting with 0x as in 0x0A.

As stated before, 1 should output 8 (0001 to 1000). So instead of while(x!=0), the code needs to shift the first bit as far as the length of the bits needed in this example it is 4.

for (int i = 0; i < 4; ++i) { // not while (x!=0){ b<<=1; b|=( x &1); x>>=1; } Hex convert 0-F: 0=0 1=8 2=4 3=C 4=2 5=A 6=6 7=E 8=1 9=9 A=5 B=D C=3 D=B E=7 F=F 

Or full 8 bit example:

public static byte reverse(byte x) { byte b = 0; for (int i = 0; i < 8; ++i) { b<<=1; b|=( x &1); x>>=1; } return b; } public static void main(String args[]) { byte[] nums = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, (byte) 0xAA, (byte) 0xFE, (byte) 0xFF }; for (byte b : nums) { System.out.printf("%02X=%02X ", b, reverse(b)); } System.out.println(); } 

Output:

00=00 01=80 02=40 03=C0 04=20 05=A0 06=60 07=E0 08=10 09=90 0A=50 0B=D0 0C=30 0D=B0 0E=70 0F=F0 10=08 11=88 AA=55 FE=7F FF=FF 

Comments

1

b is shifted left once too often. I expect input 1 to result in output 2. Move the Shift two lines up.

Comments

1

you shifted b once too many. try shifting b to the left before doing the |=:

 while (x!=0){ b<<=1; b|=( x &1); x>>=1; } System.out.println(b); 

Comments

1

You're left shifting b one time more than required. Add b >>= 1 after your while loop.

Comments

1
while(x!=0){ b<<=1; b|=(x&1); x>>=1; } 

Comments

0

The result is twice as much as expected so the last left shift operation (one left shift doubles the value) is too much.

Comments

0

It is safe to use the unsigned right shift operator (>>>) in the while loop to obviate the danger of running into an infinite loop for -ve numbers.

while (x!=0){ b<<=1; b|=( x &1); x>>>=1; } 

Comments

0

My new java code reverse bits in an integer using java with powerful bit manipulation. It is working with positive, negative and zero values. Hope it helps.

public static int reverseDigits(int num) throws Exception { if (num == 0) { return Integer.MAX_VALUE | Integer.MIN_VALUE; } int count = Integer.SIZE * 8 - 1; int reversed = num; boolean positive = true; if (num < 0) { positive = false; } if (positive) num >>= 1; while(num != 0) { reversed <<= 1; reversed |= (num & 1); num >>>= 1; count--; } if (positive) reversed <<= count; return reversed; } 

You can represent bits in integer with my other bit manipulation code in java what print zeroes on the left: https://stackoverflow.com/a/39056535/6738542

Because Integer.toBinaryString() will hide the zeroes on the left.

Metal |,,|

3 Comments

much nicer if you use this line: boolean positive = (num < 0) ? false : true; and forget the next if statement.
"throws Exception" is not important, I used it only for other tests.
or boolean positive = num>=0;
0
// i/p=3 // o/p=3221225472 // Clearly observe the 1L while doing the left shift, if ignored it will fail to return the expected output dur to mismatch in bit size. public static long reverse(long n) { long rev = 0; for(int i = 31; i >=0; i--){ if((n & 1<<i) != 0){ rev = rev | 1L<<(31-i); } } return rev; } 

Comments