We need to write a python program which converts a binary input to a decimal number.

Example:

Input:  1011
Output: 11

Input:  1111
Output: 15

Binary to Decimal

This can be achieved in multiple ways.

Convert Binary to Decimal in Python

In this method we will convert binary into decimal in a standard way. All we need to do is to 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

Convert Binary to Decimal in Python using int()

int() method can also convert a binary into an integer, if we pass the binary number along with its base (i.e 2) to int() method.

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 

Convert Binary to Decimal in Python using Recursion

This method is similar to the first example, only we are implementing it in a recursive way. In the recursive function, we are passing the binary number. Then we are multiplying the first digit of the binary number to its corresponding value of 2 raised to the power of its index (i.e position from the right end – 1). Then we need to add the result of multiplication to the next recursive call by passing the updated binary (i.e removing the first digit). This process will continue until the single last digit of the number. The result of each recursive call will be added and finally will be returned to the first recursive function call.

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 

If you have any suggestion or doubts then comment below.

This Post Has One Comment

  1. Ekta
    
    print("---------------without using len function-----------------------")
    binary = int(input('Enter a Binary number: '))
    deci=0
    p=0
    while binary>0:
        q=binary//10
        r=binary%10
        deci = deci + r*2**p
        p +=1
        binary=q
    print(" Decimal is ", deci)

Leave a Reply