Numbers · beginner
Python Program to Convert Decimal to Binary
Convert a decimal number to binary in Python by repeated division by 2, then with bin() and format(), and convert binary back to decimal with int(text, 2).
- while loop
- divmod()
- string building
- bin() and int(x, 2)
Computers store numbers in binary (base 2), using only the digits 0 and 1. To convert a decimal number by hand, divide it by 2 again and again and write down the remainders; read from last to first, they are the binary digits.
The program
def to_binary(n):
if n == 0:
return "0"
bits = ""
while n > 0:
n, remainder = divmod(n, 2)
bits = str(remainder) + bits
return bits
for n in [10, 255, 0]:
print(n, "->", to_binary(n))10 -> 1010
255 -> 11111111
0 -> 0How it works
- divmod(n, 2) returns the quotient and the remainder in one call: divmod(10, 2) is (5, 0).
- The remainder is the next binary digit, from right to left, so it is put in front of the string built so far.
- n becomes the quotient, and the loop repeats until n is 0: 10 → 5 → 2 → 1 → 0 gives the remainders 0, 1, 0, 1, so 10 is 1010.
- Zero needs a special case, because the loop would not run and the result would be an empty string.
Watch it run line by line
Visualize to_binary(10) and watch bits grow from the left: "0", "10", "010", "1010", while n halves on every pass.
“Visualize step by step” opens the program in the Python Compiler and records every step in your browser. Use the arrow keys to move forwards and backwards; changed variables are highlighted.
Another way: Built-in conversions
bin() adds a 0b prefix, format(n, "b") does not, and format(n, "08b") pads to 8 digits. int(text, 2) converts back from binary.
print(bin(10))
print(format(10, "b"), format(10, "08b"))
print(int("1010", 2))0b1010
1010 00001010
10Common mistakes
- Appending the remainders instead of prepending them, which gives the binary digits in reverse order.
- Forgetting the case n == 0, so the function returns an empty string.
- Calling int("0b1010") without a base: it raises ValueError. Use int("0b1010", 0) or int("1010", 2).
Try it yourself
- Change the function so it converts to any base from 2 to 16 (use "0123456789ABCDEF" for the digits).
- Count the 1 bits in 255 with bin(255).count("1").
Open the program in the Python Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.
Related examples
Browse all 25 Python examples, or write your own program in the online Python Compiler.