Decimal to Binary in Python

We know that the computer only understands binary numbers that are 0 and 1. All data are given as input to the computer converts into a binary number system. We have discussed how to convert decimal to binary in python. In the same way, conversion of Binary to Decimal, Decimal to Octal and Octal to Decimal, Octal to Binary and Binary to Octal also can be done.

We will be given a decimal number and the python program to convert the given decimal number into an equivalent binary number.

Example:-

Decimal number: 9
Binary number: 1001

Python Decimal to Binary Program

This is the simplest and easiest program in python because this program used a built-in function. We will take the decimal number when declaring the variable and print the binary value of the number using the bin() function.

# Python program to convert decimal to binary

# take input
num = int(input('Enter any decimal number: '))

# display result
print('Binary value:', bin(num))

Output for different input values:-

Enter any decimal number: 2
Binary value: 0b10

Enter any decimal number: 5
Binary value: ob101

Enter any decimal number: 9
Binary value: 0b1001

How To Convert using Recursion

A function/method that contains a call to itself is called the recursive function/method. A technique of defining the recursive function/method is called recursion. The recursive function/method allows us to divide the complex problem into identical single simple cases that can handle easily. This is also a well-known computer programming technique: divide and conquer.

# Python program to convert decimal to binary using recursion

def DecimalBinary(n):   #user-defined function
    if n >= 1:
        DecimalBinary(n // 2)
    print(n % 2, end = '')
 
# take input
num = int(input('Enter any decimal number: '))

# calling function and display result
print('Binary value: ')
DecimalBinary(num)

Output:-

Enter any decimal number: 13
Binary value:
1101

Python Program to Convert Decimal to Binary using While loop

This is the different method to convert decimal to binary in python. In this program, we have an import math module and using the while loop to convert decimal to binary.

# Python program to convert decimal to binary using while loop

import math  #importing math-module

# take input
num = int(input('Enter any decimal number: '))

rem=''
while num>=1:
    rem+=str(num%2)
    num=math.floor(num/2)

# convert binary
bin=""
for i in range(len(rem)-1,-1,-1):
    bin = bin + rem[i]

# display result
print('Binary value:', bin)

Output:-

Enter any decimal number: 3
Binary value: 11

Also See:-

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

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