convert decimal to binary in Python

Python PythonBasic

In this post, we are going to convert decimal to binary in Python with examples using built-in bin(), format() and f-string and recursion.

1.Bin() function convert decimal to binary in Python


In this example, we are using the bin() function to convert binary to decimal. It adds “0b” as the prefix of string representation using replace() to replace “0b” to ” “.

Python 3 program to convert Decimal to binary

def Dec_to_bin(num):
    decimal_num = bin(num).replace("0b", "")
    print(decimal_num)

Dec_to_bin(13)

Output

1101

2. str.Format() to convert decimal to binary


In this example, we are using str.format() to convert decimal to binary. The str. format() method can be used to convert a number to binary using string presentation “b”.

Python Program Example

num = 45
decimal_num = "{0:b}".format(int(num))
print(decimal_num)

Output

101101

3. F-string to decimal to binary


In this example we are going to learn f-string. Python version 3.6 introduced the formatted string literal also known as “f-string”.The“f-string” is used for formatting the string and is easy to use and readable. To use it we have to start the string with “F” or “F” before quotation marks and write a Python expression or variable that contains literal values between { } that are evaluated at runtime. 

Python Program to convert decimal to binary

num = 45
decimal_num = f"{num:b}"
print(decimal_num)

Output

101101

4. Recursion to Convert decimal to binary in Python


In this example, we are recursively converting decimal to binary in Python by defining a custom function dec_tobin() and calling it recursively.

Python Program to Convert decimal to binary

def dec_tobin(val):
     
    if val >= 1:
        dec_tobin(val // 2)
    print(val % 2, end = '')


dec_tobin(45)

Output

101101

5. While loop to Convert decimal to binary in Python


In this example, we are using a while loop to Convert decimal to binary in Python.

Python Program Example

decNum = int(input("Please Enter a decimal number \n"))
bin_val = 0
count = 0
tval = decNum 


while(tval > 0):
    bin_val = ((tval%2)*(10**count)) + bin_val
    tval = int(tval/2)
    count += 1
    

print("Binary of {decnum} is: {bin_val}".format(decnum=decNum,bin_val=bin_val))

Output

Please Enter a decimal number 
35
Binary of 35 is: 100011

Summary

In this post, we have learned how to convert decimal to binary in Python with examples by using built-in bin(), format(), and f-string and recursively.