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?
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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With