Problem: Write a Python program to convert a binary number into its corresponding decimal representation.
Example:
Input: 1011 Output: 11 Input: 1111 Output: 15
Method 1: Convert Binary to Decimal using for loop
In this method, we multiple each of the binary digits with its corresponding value of 2 raised to the power to its index (position from right – 1) and sum them up.
binary = input('Enter a Binary number: ')
decimal = 0
#length of binary input
l = len(binary)
#loop through each digit of binary
for x in binary:
l = l-1 #decrease l by 1
decimal += pow(2,l) * int(x) #multiply
print("Decimal of {p} is {q} ".format(p=binary, q=decimal))
Output:
Enter a Binary number: 1111
Decimal of 1111 is 15 decimal
Method 2: Convert Binary to Decimal using int()
We can easily convert binary to a decimal using the built-in int() function. To do this, we pass the binary number along with its base (i.e 2) as parameters to the int()
function.
binary = input('Enter a Binary number: ')
#since binary base is 2, so pass 2 as 2nd argument
decimal = int(binary,2)
print("Decimal of {p} is {q} ".format(p=binary, q=decimal))
Output:
Enter a Binary number: 1011
Decimal of 1011 is 11
Method 3: Convert Binary to Decimal using Recursion
This method is similar to the first example, only we are implementing it in a recursive way.
def binToDec(x):
if x == 1 or x == 0:
return x
l = len(str(x))
firstDigit = x//pow(10,l-1)
return (pow(2,l-1) * firstDigit)+ binToDec(x%pow(10,l-1))
binary = int(input('Enter a Binary number: '))
decimal = binToDec(binary)
print("Decimal of {p} is {q} ".format(p=binary, q=decimal))
Output:
Enter a Binary number: 101
Decimal of 101 is 5
In this, we write a recursive function that accepts a binary number in its arguments.
In the function, we multiply the first digit of the number to its corresponding value of 2 raised to the power of its index (i.e position from the right end – 1).
Then we add the result of multiplication to the result of the next recursive call.
To make a recursive call, we pass the updated binary (i.e number after removing the first digit) to the same function.
This process continues until the single last digit of the binary number. Because of this, the results of each recursive get added and we get the decimal representation of the given binary number.
One thought on “Python Program to Convert Binary to Decimal”