Home / Python / Example programs / Loops and numbers

Python program: Convert decimal to binary

Convert whole numbers to binary by repeated division by 2, and check with bin().

The code

def to_binary(n):
    if n == 0:
        return "0"
    bits = ""
    while n > 0:
        bits = str(n % 2) + bits
        n //= 2
    return bits

for n in [0, 5, 10, 255]:
    print(n, to_binary(n), bin(n)[2:], int(to_binary(n), 2))

Output

0 0 0 0
5 101 101 5
10 1010 1010 10
255 11111111 11111111 255

How it works

The remainders of repeated division by 2, read in reverse, are the binary digits. int(text, 2) converts back.

Python features used

Learn the ideas behind it in the free lesson Loops.