In this post, we will learn how to convert decimal to binary in Python with a simple explanation and example but before we jump into programming part let’s see the overview.
Decimal numbers are a number system that consists of 10 digits from 0 to 9. Using these numbers, it forms all other numbers. On the other hand, binary numbers consist of two digits, 0 and 1, and using these two digits, it forms all other numbers.
Now, let’s see the mathematical approach to convert a decimal number to a binary number with the help of an example.
Convert Decimal to Binary
Let’s suppose you have the number 6, and you want to convert it into a binary number. Just take that number (6) and divide it by 2. Then, store the remainder of the division (6%2). In the next step, take the quotient (3) and divide it by 2, and again, store the remainder of this division. Continue this process until you reach 0. Finally, reverse the order of the stored remainders to obtain the binary conversion.
For a better understanding, please refer to the figure below:
Algorithm
- Take input from the user (
n
). - Create an empty list to store binary numbers (
binary_list
). while n!=0
do
rem = n%2
binary_list.append(rem)
n = n//2
- Reverse the
binary_list
using slicing ([::-1]
) . - print the
binary_list
From the above algorithm and explanation, we now know how to write a program in Python to convert a decimal number to a binary number. However, before writing the program, there are a few programming concepts you need to be familiar with.
Source Code
n = int(input("Enter a number:"))
# Create a Empty list to store binary numbers
binary_list = []
# store remainders using while loop
while n!=0:
rem = n%2
binary_list.append(rem)
n = n//2
# Reverse a list
binary_list = binary_list[::-1]
# print binary numbers
print("Binary of given number is ",end='')
for num in binary_list:
print(num, end='')
Output-1
Enter a number:6
Binary of given number is 110
Output-2
Enter a number:10
Binary of given number is 1010
Convert Decimal to Binary Using Built-in Function
We can also use a built-in function called the bin()
function to convert decimal to binary.
Source Code
num = int(input('Enter a number: '))
binary = bin(num)
print(f"Binary of {num} is {binary}")
Output
Enter a number: 10
Binary of 10 is 0b1010
The first two digits 0b
, indicate that it is a binary expression and the remaining digits are the actual binary representation, which is 1010
.