Python Program for Binary To Decimal Conversion

Binary to Decimal Conversion

In this article we will discuss binary to decimal conversion in Python. For this purpose we need to take a binary integer number from user and convert that binary integer number to its decimal equivalent form and then print the converted number on to the screen. A Decimal number can be calculated by multiplying every digits of binary number with 2 to the power of the integers starts from 0 to n-1 where n refers as the total number of digits present in a binary number and finally add all of them.

Binary to decimal conversion

Working :

 A Decimal number can be calculated by multiplying every digits of binary number with 2 to the power of the integers

 starts from 0 to n-1 where n refers as the total number of digits present in a binary number and finally add all of them.

Methods Discussed :

  1. Algorithmic way (Binary to Decimal)
  2. Inbuilt Method (Binary to Decimal)

Method 1

Algorithm :

  • While num is greater then zero
  • Store the unit place value of num to a variable (rem)
  • Calculate rem with base and add it to answer
  • Completely divide Num by 10 and multiply base with 2

Time and Space Complexities

  • Time Complexity – O(N), where N is the count of the digits in the binary number
  • Space Complexity – O(1), Constant Space

Python Code :

Run
num = 10
binary_val = num
decimal_val = 0
base = 1

while num > 0:
    rem = num % 10
    decimal_val = decimal_val + rem * base
    num = num // 10
    base = base * 2

print("Binary Number is {}\nDecimal Number is {}".format(binary_val, decimal_val))

Output :

Binary Number is 10
Decimal Number is 2

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

31 comments on “Python Program for Binary To Decimal Conversion”


  • Jerriporhula

    binary=input()
    b=binary[::-1]
    decimal=0
    for i in range(len(binary)):
    decimal=decimal+int(b[i])*(2**i)
    print(decimal)


  • krajendraprasad553

    def binarytodecimal(n):
    d=int(n)
    sum=0
    p=0
    while d>0:
    r=d%10
    sum=sum+(r*2**p)
    d=d//10
    p+=1
    print(sum)
    n=eval(input(‘enter a binary value:’))
    binarytodecimal(n)


  • K. Srujan

    def get_decimal(binary):
    size = len(binary)
    decimal = 0
    for i in range(size):
    decimal += int(binary[(size – i) – 1]) * (2 ** i)
    return f”Binary : {binary}\nDecimal : {decimal}”

    binary_input = input()
    print(get_decimal(binary_input))


  • Pranudh

    num=int(input())
    decimal=0
    power=0
    while num>0:
    rem=num%10
    decimal+=rem*(2**power)
    num=num//10
    power+=1
    print(decimal)


  • Taddi

    binary=int(input())
    l=len(str(binary))
    sum=0
    for i in range(l):
    sum+=binary%10*pow(2,i)
    binary//=10
    print(sum)