Exercise: Binary to Decimal

Write a console program that

  1. reads a binary number such as 101 as a string from the user,
  2. converts the binary number to a decimal number, and
  3. prints the decimal number.

Example program output (user input in green):

Enter a binary number:
11111110
11111110 in decimal is 254
Enter a binary number:
101
101 in decimal is 5

How to convert binary to decimal

Each bit in a binary number represents a power of 2. The rightmost bit represents 20 (which is 1), the next bit to the left represents 21, the next bit to the left represents 22, and so on. Consider the binary number 111001 and its values in decimal:

bits: 1 1 1 0 0 1
bit values: 25 24 23 22 21 20
If the bit is 1, you add the corresponding power of 2 to the decimal number. If the bit is 0, you skip it. In this example, the decimal value of 111001 is 57 because (going from right to left):

2 0 + 2 3 + 2 4 + 2 5 = 1 + 8 + 16 + 32 = 57

Hints 💡

Hand in instructions

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