Convert A Decimal To Binary In Python

This tutorial will be focussed to discuss different ways to convert a decimal to binary in python. So without further ado let’s get started.

In mathematics and digital electronics decimal and binary are both the number systems to represent a number.

In the binary number system, A number is expressed in the base-2 numeral system and represented in terms of 0 and 1.

In the decimal number system, A number has 10 as its base and represented by 10 digits 0,1,2,3,4,5,6,7,8,9.

1. By Using Recursion

In computer science, Recursion is a technique to solve a problem where a function calls itself directly or indirectly.

Every recursive solution has a base case and the larger problem can be expressed in terms of tinier problems.

In this code example, we will use the recursion technique of programming to convert the decimals to binary in python.

# program1 to convert a decimal to binary in python
def convert(decimal):
    if decimal > 1: 
        convert(decimal // 2) 
    print(decimal % 2, end = '') 

decimal = 10


Here is the output of the above code.

Output :

Output of the program to convert a decimal to binary in python

2. By Using Builtin bin() Function

The bin(number) is the builtin function in python that takes a number as its argument and returns its binary representation.

In the following code, we will use the builtin bin() function to convert decimals to binary.

# program 2 to convert a decimal to binary in python
def convert(decimal):
    return bin(decimal).replace("0b", "") 

decimal = 10
binary = convert(decimal)

print(f"Binary of {decimal} :",binary)

Also read about how to find square root in python.

Leave a Reply