Binary To Decimal Conversion In Python

Binary To Decimal Conversion In Python

Published on July 20 2023

In this tutorial you will see how to convert binary numbers into decimal numbers using logical implementation. Also, we will use built in methods and understand each line in detail.

Source code

# Method - 1 - Using Custom Logic

binary_number = int(input("ENter binary number - only allowed 0s and 1s:"))

def binary_to_decimal(binNum):

    decimal_number = 0
    power = 0

    while binNum != 0:
        decimal = binNum % 10
        decimal_number = decimal_number + decimal * pow(2, power)

        binNum = binNum // 10
        power +=1

    return decimal_number

output = binary_to_decimal(binary_number)
print('Decimal :', output)

# Method - 2 - Using Built In Method - int()

binary_number = input("ENter binary number - only allowed 0s and 1s:")
output = int(binary_number, 2)
print('Decimal:', output)