Editor

Python Program to Convert Binary to Decimal

Beginner · Numbers

In a binary number each digit stands for a power of 2: from the right, the places are worth 1, 2, 4, 8, 16 and so on. To convert binary to decimal, you add up the place values of the digits that are 1, and this program does that step by step.

Program

binary_to_decimal.py
binary = "101101" # or: binary = input("Enter a binary number: ")
decimal = 0
power = 0
# Go through the digits from right to left
for digit in reversed(binary):
place_value = int(digit) * 2 ** power
print(f"{digit} x 2^{power} = {place_value}")
decimal += place_value
power += 1
print("Binary:", binary)
print("Decimal:", decimal)
Output
1 x 2^0 = 1
0 x 2^1 = 0
1 x 2^2 = 4
1 x 2^3 = 8
0 x 2^4 = 0
1 x 2^5 = 32
Binary: 101101
Decimal: 45

How it works

  1. reversed(binary) gives the digits from right to left, so the first digit visited is the ones place.
  2. Each digit is multiplied by 2 ** power, the value of its place, and added to decimal.
  3. power goes up by 1 with each place, so the places are worth 1, 2, 4, 8, 16, 32 and so on.
  4. The printed steps show which powers of 2 add up: 1 + 4 + 8 + 32 = 45.

Other ways to write it

Using int() with base 2

Using int() with base 2
for binary in ["101101", "1111", "10000000"]:
print(binary, "in decimal is", int(binary, 2))
print("Hex ff in decimal is", int("ff", 16))
Output
101101 in decimal is 45
1111 in decimal is 15
10000000 in decimal is 128
Hex ff in decimal is 255

int() takes the base as a second argument, so int("101101", 2) reads the text as binary, and the same works for base 8 or 16.

Binary digits stored as a number

Binary digits stored as a number
binary = 101101 # the digits typed as an ordinary number
decimal = 0
power = 0
while binary > 0:
digit = binary % 10 # the last digit, 0 or 1
decimal += digit * 2 ** power
binary //= 10 # drop the last digit
power += 1
print("Decimal:", decimal)
Output
Decimal: 45

Many textbooks store the binary digits as a whole number and peel them off with % 10 and // 10, the same trick used to find the sum of digits.

Try it yourself

Add a check that prints an error message when the text contains any digit other than 0 or 1.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises