What I'm trying to do is convert any number up to 2^32 - 1 that is input by the user to its binary value using only bitwise operators. After much head scratching and tinkering, I've come to this conclusion that seems to be giving me what I want... almost:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter a number: ");
String input = scan.nextLine();
int dec = Integer.parseInt(input);
ArrayList<Integer> binary = new ArrayList<Integer>();
for (int i = 0; i < 32; i++) {
if ((dec & 1) == 0) {
binary.add(0);
} else {
binary.add(1);
}
dec = dec >>> 1;
}
Object[] binaryArray = binary.toArray();
for (int i = binaryArray.length - 1; i >= 0; i--) {
System.out.print(binaryArray[i]);
}
}
Here's my problem now: This does output the proper binary string, but I need to remove the leading zeros so that the decimal number 10 comes out as 1010 in binary rather than 00000000000000000000000000001010.
I'm a first semester CS student, so any help on solving the issue or tips on cleaning up the code would be greatly appreciated.
Reading your code a third time, I noticed something that's a bit tricky. What you're doing is OK, but there might be a better way. I'm not going to give the answer, but I want to look at something different.
The ArrayList
in your code is not needed. What if you wrote the code this way?
for (int i = 1 << 31; i != 0; i = i >>> 1) {
if ((dec & i) == 0) {
System.out.print( "0" ); //binary.add(0);
} else {
System.out.print( "1" ); //binary.add(1);
}
}
Here I simply "print as I go." The ArrayList
and the conversion to an array are unneeded. I've already got one loop working and I don't need to add a second loop to print all the values of the array, because I just use the loop I already have.
OK, so the first bit of code I had was wrong. It prints in the reverse order. This code (should! untested!) starts at bit #32 and count down from there, printing the bits in order. It also shows how you can use other things in a for
loop, like i = i >>> 1
instead of just always doing ++
.
Elaborating on the hint: A quick way to "see" what you code is doing is to print important values as your code runs. For example, to get an idea what you might do with dec
, add a print statement to print its value. Some people say to use a debugger and step through code but I find print statements to be faster.
for( int i = 0; i < 32 ; i++ ) {
if( (dec & 1) == 0 ) {
binary.add( 0 );
} else {
binary.add( 1 );
}
dec = dec >>> 1;
System.out.println( "DEBUG: " + dec );
}