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
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
reversed(binary)gives the digits from right to left, so the first digit visited is the ones place.- Each digit is multiplied by
2 ** power, the value of its place, and added todecimal. powergoes up by 1 with each place, so the places are worth 1, 2, 4, 8, 16, 32 and so on.- 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
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
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.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises