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.
decwhen you do that enough times. - markspacedecas "decimal." All numbers (and strings/letters) in a computer are actually stored in a binary format. What you're printing now is actually how the number is really formatted inside a computer. - markspaceInteger.parseInt(input);. Everything after it is a complete waste of time and space. - user207421Integer.toBinaryString. - Andy