Write a console program that lets the user enter a positive decimal number. Convert that number to its binary form and print it.
Example program output (user input in green):
Enter a decimal number:
13
13 in binary is 1101.
Enter a decimal number:
0
0 in binary is 0.
Enter a decimal number:
254
254 in binary is 11111110.
For example, to convert the decimal number 13 to binary:
Decimal number | Quotient | Remainder |
---|---|---|
13 | 6 | 1 |
6 | 3 | 0 |
3 | 1 | 1 |
1 | 0 | 1 |
1101
.
Why does repeatedly dividing the number by 2 and saving the remainder give us the binary representation of that number?
One way to look at this is that the remainder of the division by 2 (in Java: %2
) is the rightmost bit of the binary representation. The rightmost bit is also called the least significant bit. It's 0
for even numbers and 1
for odd numbers.
The quotient of the division by 2 (in Java: /2
) is the number that remains when you remove the least significant bit by shifting the bit sequence one bit to the right.
If you repeat this process with the quotient, you get the next bit of the binary representation and so on.
Consider the binary representation of the decimal number 116, its least significant bit, and how those change after each division by 2:Decimal number | Number in binary | Least significant bit |
---|---|---|
116 | 1110100 | 0 |
58 | 111010 | 0 |
29 | 11101 | 1 |
14 | 1110 | 0 |
7 | 111 | 1 |
3 | 11 | 1 |
1 | 1 | 1 |
Going from bottom to top, you can see the binary representation of 116: 1110100
%2
gets the rightmost bit, and /2
shifts the bits to the right.
bits: | 1 | 1 | 1 | 0 | 1 | 0 | 0 |
---|---|---|---|---|---|---|---|
bit values: | 26 | 25 | 24 | 23 | 22 | 21 | 20 |
1110100
: