PythonMastery

Convert binary to decimal and back in Python

Convert a decimal number to binary, octal and hexadecimal with format(), turn binary text back into a number with int(text, 2), and do both by hand.

Python has built-in tools for number bases: format() writes a number in base 2, 8 or 16, and int(text, base) reads it back.

The program

python
n = int(input("Decimal number: "))
print("Binary:     ", format(n, "b"))
print("Octal:      ", format(n, "o"))
print("Hexadecimal:", format(n, "X"))

text = input("Binary number: ")
print("Decimal:    ", int(text, 2))

Typed in this example: 42, 11111111. Press Run to type your own.

output
Decimal number: 42
Binary:      101010
Octal:       52
Hexadecimal: 2A
Binary number: 11111111
Decimal:     255

How it works

By hand

To convert to binary, divide by 2 again and again. The remainders, read from last to first, are the binary digits. To convert back, start at 0 and, for each digit, double the total and add the digit:

python
def to_binary(n):
    if n == 0:
        return "0"
    sign = "-" if n < 0 else ""
    n = abs(n)
    digits = ""
    while n > 0:
        digits = str(n % 2) + digits
        n //= 2
    return sign + digits


def from_binary(text):
    total = 0
    for digit in text:
        total = total * 2 + int(digit)
    return total


for n in [0, 5, 42, 255, -6]:
    print(n, to_binary(n))
print(from_binary("101010"))
output
0 0
5 101
42 101010
255 11111111
-6 -110
42

from_binary() here only handles positive numbers without a sign. The built-in int(text, 2) also accepts a sign and the 0b prefix: int("-110", 2) and int("0b110", 2) both work.

Learn the idea: Numbers in Depth: Integers, Floats, and the math Module, F-Strings: Modern String Formatting