07.binary decimal

Convert decimal number to binary

def decimalToBinary(num):
    if num > 1:
        decimalToBinary(num // 2)
    print(num % 2, end='')
decimalToBinary(10)
1010

Pythonic way to convert decimal to binary

Python has bin() method to convert decimal numbers into binary. The bin() method converts and returns the binary equivalent string of a given integer.

decimal = int(input("Enter a decimal number :"))

binary = bin(decimal).replace("0b", "")  
print("The binary number is :", binary)
Enter a decimal number :10
The binary number is : 1010

Convert binary to decimal number

def binaryToDecimal(binary): 

    decimal = 0 

    for digit in binary: 
        decimal = decimal*2 + int(digit) 
        print(int(digit))
        print('decimal', decimal)
    print("The decimal value is:", decimal)
binaryToDecimal('10')
1
decimal 1
0
decimal 2
The decimal value is: 2

def binaryToDecimal(binary):
    value = 0

    for i in range(len(binary)):
        digit = binary.pop()
        if digit == '1':
            value = value + pow(2, i)

    print("The decimal value of the number is", value)
binary = list(input("Enter a binary number:"))

binaryToDecimal(binary)
Enter a binary number:10
The decimal value of the number is 2

Pythonic way to convert binary into decimal

We can use the built-in int() function to convert binary numbers into decimals. The int() function converts the binary string in base 2 number.

binary_string = input("Enter a binary number :")

try:
    decimal = int(binary_string, 2)  
    print("The decimal value is :", decimal)    

except ValueError:
    print("Invalid binary number")
Enter a binary number :20
Invalid binary number