Exercise: Binary to Decimal
Write a console program that
- reads a binary number such as
101
as a string from the user,
- converts the binary number to a decimal number, and
- 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):
Hints 💡
- Since the binary number is a string, you can use the
charAt
method to access each character in the string. For example, binary.charAt(0)
returns the leftmost character in the string, and binary.charAt(binary.length() - 1)
returns the rightmost character in the string.
- Because the values of the binary digits (bits) increase from right to left, you can start from the rightmost digit and work your way to the leftmost digit. A loop counting backwards from the rightmost digit to the leftmost digit is a good way to solve this problem.
- Exponentiation can be done using the
Math.pow
method in Java.
Hand in instructions
- Make sure your program runs correctly.
- Hand in your program by uploading Main.java to Moodle.