Convert Binary to Decimal in Python

Left to right: double, add the bit. 1010 → 10. Reject anything that isn't 0 or 1.

BeginnerBasic Python ProgramsExample 24 of 25
convert-binary-to-decimal.py
Run in browser
1# Program to convert binary to decimal without using int(x, 2)
2
3binary_str = input("Enter a binary number: ")
4
5if not all(ch in '01' for ch in binary_str):
6 print("Invalid binary number.")
7else:
8 decimal_value = 0
9 for ch in binary_str:
10 decimal_value = decimal_value * 2 + int(ch)
11
12 print(f"Decimal value of {binary_str} is {decimal_value}")

Output

Enter a binary number: 1010
Decimal value of 1010 is 10

In this one

  • double, add bit, repeat
  • reject characters that aren't 0 or 1

What's going on

Start at 0. For each bit: double what you have, add the bit.

1010:

0×2+1=1

1×2+0=2

2×2+1=5

5×2+0=10

int(binary_str, 2) does this. The loop is the same algorithm with the lid off.

all(ch in '01' for ch in binary_str) dumps 1021 early. int('1021', 2) would throw. Catching it yourself is nicer.