Write a Python program to convert decimal to binary
In this post, you will learn how to convert a decimal into an equivalent binary number using Python programming language. Here, we have mentioned three ways to convert a decimal to binary number.
Using recursive function
A recursive function is a function that calls itself during its execution. For this, we have defined a function and taken a decimal number as an input and convert to equivalent binary number.
# Function to convert a
# decimal number to binary
def convertDecimalToBinary(x):
if x > 1:
convertDecimalToBinary(x // 2)
print(x % 2, end='')
# Get user input
num = int(input("Enter a decimal number: "))
convertDecimalToBinary(num)
Output of the above code -
Enter a decimal number: 23
10111
Enter a decimal number: 53
110101
Enter a decimal number: 90
1011010
Using bin() function
The bin() is an inbuilt function of Python that takes a decimal value and returns an equivalent binary representation of that. The following example demonstrates this -
Enter a decimal number: 52
Equivalent Binary Number: 110100
Enter a decimal number: 84
Equivalent Binary Number: 1010100
Enter a decimal number: 93
Equivalent Binary Number: 1011101
Without inbuilt function
The following program converts a decimal to binary number without using any inbuilt function -
# Function to convert a
# decimal number to binary
def convertDecimalToBinary(num):
return "{0:b}".format(int(num))
# print equivalent binary number
if __name__ == '__main__':
print("Equivalent Binary Number: ",convertDecimalToBinary(43))
print("Equivalent Binary Number: ",convertDecimalToBinary(14))
print("Equivalent Binary Number: ",convertDecimalToBinary(70))
Output of the above code -
Equivalent Binary Number: 101011
Equivalent Binary Number: 1110
Equivalent Binary Number: 1000110
Related Articles
Convert list to dictionary Python
Convert array to list Python
numpy dot product
glob in Python
Python heap implementation
zip function in Python
Remove last element from list Python
Check if list is empty Python
Remove element from list Python
Python split multiple delimiters
Python loop through list
Python iterate list with index
Python add list to list
Python random choice
Python dict inside list
Remove character from string Python
Python raise keyword