Exercise: Decimal to Binary

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.

How to convert decimal to binary

The steps to convert a decimal number to binary are as follows:
  1. Start with the decimal number.
  2. Get the remainder of the number when divided by 2.
  3. Divide the decimal number by 2.
  4. Repeat steps 2 and 3 until the decimal number is 0.
The binary number is the sequence of remainders from step 2, read from the last remainder to the first remainder.

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
Therefore, the binary representation of 13 is 1101.

Why does it work?

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

In short, this method works because %2 gets the rightmost bit, and /2 shifts the bits to the right.

Verifying the conversion

Once we have converted from decimal to binary, we can convert from binary to decimal again, to make sure the conversion is correct:
bits: 1 1 1 0 1 0 0
bit values: 26 25 24 23 22 21 20
Going from right to left, we calculate the decimal value of 1110100:

2 2 + 2 4 + 2 5 + 2 6 = 4 + 16 + 32 + 64 = 116

Hand in instructions

  1. Make sure your program runs correctly.
  2. Hand in your program by uploading Main.java to Moodle.