In this Python example we will convert a decimal number into its corresponding binary form.

E.g 15 -> 1111

decimal to binary

Recommended:

Convert Decimal to Binary in Python without bin()

In this method, we are taking a decimal number as input and dividing it by 2 until the number reduces to 0. All the remainder is concatenated together in bottom-up manner.

decimal = int(input("Enter a decimal number \n"))
binary = 0
ctr = 0
temp = decimal  #copying number

#calculating binary
while(temp > 0):
    binary = ((temp%2)*(10**ctr)) + binary
    temp = int(temp/2)
    ctr += 1
       
print("Binary of {x} is: {y}".format(x=decimal,y=binary))

Output

Enter a decimal number 
2
Binary of 2 is: 10

Enter a decimal number 
7
Binary of 7 is: 111

Enter a decimal number 
15
Binary of 7 is: 1111

Convert Decimal to Binary in Python using Recursion

In this python program, we are using recursion to convert the decimal into binary number. On each recursive call we are passing the quotient (dividend/2) as the parameter.

Since it is a tail recursion, the remainder will be printed from last-remainder to first-remainder (bottom up manner ).

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()

print(bin(15))

Output

0b1111

If you have any doubts then comment below.

Leave a Reply

3 + 10 =