Python Practice › Basic Programs › Program 34
Convert decimal to binary
Write a Python program to convert a decimal number to binary.
Input
25
Output
11001
Approach
- Repeatedly divide by 2 and collect the remainders, then read them in reverse. Or use
bin().
Solution 1: by hand
n = 25bits = ""while n > 0: bits = str(n % 2) + bits n //= 2print(bits)Output
11001
Line by line
Line 4
The remainder after dividing by 2 is the next binary digit; adding it in front reverses the order for us.
Line 5
Integer division moves to the next digit.
Solution 2: built-in
print(bin(25), format(25, "b"), int("11001", 2))Output
0b11001 11001 25
Line by line
Line 1
bin() adds the 0b prefix, format(n, "b") does not, and int(text, 2) converts back.
Learn the concept
New to this topic? Read the lesson, then come back.