Convert Decimal to Binary in Python [3 Methods]

python programs

Problem: Write a Python Program to convert a decimal number into its corresponding binary representation using Python language.

Example:

Input: 15
Output: 111

In Python, we can solve this problem in 3 ways. Let’s see each of them one by one.

Convert Decimal to Binary in Python using While Loop

decimal to binary

In this method, we accept the decimal number as an input and divide it by 2 until it is reduced to 0.

We then concatenate the remainders computed as the result of the division in a bottom-up manner to form the binary bumber.

#get input and initialize variables
decimal = int(input("Enter a decimal number \n"))
binary = 0
ctr = 0
temp = decimal  #copy input decimal

#find binary value using while loop
while(temp > 0):
    binary = ((temp%2)*(10**ctr)) + binary
    temp = int(temp/2)
    ctr += 1

#output the result       
print("Binary of {x} is: {y}".format(x=decimal,y=binary))

Output:

Enter a decimal number 
2
Binary of 2 is: 10

Convert Decimal to Binary in Python using Recursion

In this method, we implement the logic of the previous method in recursive way to convert decimal into binary.

We pass the quotient (dividend/2) as a parameter to every recursive call and recursively divide it by 2.

To stack the remainders in bottom-up manner, we use the technique of the tail recursion i.e., print remainders after the recursive call.

def dectobin(decimal):
    if(decimal > 0):
        dectobin((int)(decimal/2))
        print(decimal%2, end='')
        
decimal = int(input("Enter a decimal number \n"))
dectobin(decimal)

Output:

Enter a decimal number 
5
Binary of 5 is: 101

Convert Decimal to Binary in Python using bin()

In this method, we use the built-in Python bin() method to convert an integer into its corresponding binary representation.

>>> print(bin(15))
0b1111

These were the 3 different methods using which we can easily transform any decimal number into a binary number in Python.

Leave a Reply

Your email address will not be published. Required fields are marked *