Skip to content
Advertisement

Reverse bits in number

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?

Advertisement

Answer

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;
}
2 People found this is helpful
Advertisement