Binary and Decimal Conversions
Convert decimal number to binary
def decimalToBinary(num):
if num > 1:
decimalToBinary(num // 2)
print(num % 2, end='')
decimalToBinary(10)
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)
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')
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)
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")