Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse bits in number

Tags:

java

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?

like image 637
dato datuashvili Avatar asked Jul 02 '10 12:07

dato datuashvili


2 Answers

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;
}
like image 133
Thomas Avatar answered Sep 23 '22 23:09

Thomas


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.

like image 40
Tansir1 Avatar answered Sep 26 '22 23:09

Tansir1