PythonMastery

Convert decimal to binary, octal and hexadecimal in Python

Convert a decimal number to binary, octal and hexadecimal with bin(), oct(), hex() and format(), and to binary by hand with repeated division by 2.

Python has a built-in function for each base: bin() for base 2, oct() for base 8 and hex() for base 16. Each one returns a string with a prefix that shows the base.

The program

python
n = int(input("Enter a whole number: "))

print("Binary:     ", bin(n))
print("Octal:      ", oct(n))
print("Hexadecimal:", hex(n))

Typed in this example: 2026. Press Run to type your own.

output
Enter a whole number: 2026
Binary:      0b11111101010
Octal:       0o3752
Hexadecimal: 0x7ea

How it works

Without the prefix

format() and f-strings use the codes b, o, x and X without a prefix. A number before the code sets the width, and a 0 in front fills the space with zeros:

python
for n in [5, 10, 15, 16, 255]:
    print(f"{n:>3}  {n:08b}  {n:>3o}  {n:>2X}")

print(format(2026, "b"), f"{2026:#x}")
output
  5  00000101    5   5
 10  00001010   12   A
 15  00001111   17   F
 16  00010000   20  10
255  11111111  377  FF
11111101010 0x7ea

08b writes the number as 8 binary digits, which is one byte. # adds the prefix back.

By hand: divide by 2

To convert to binary by hand, divide by 2 again and again and write down each remainder. The remainders, read from the last one to the first, are the binary digits:

python
n = 13
digits = []

while n > 0:
    remainder = n % 2
    print(f"{n:>2} // 2 = {n // 2}, remainder {remainder}")
    digits.append(str(remainder))
    n //= 2

print("Binary:", "".join(reversed(digits)))
output
13 // 2 = 6, remainder 1
 6 // 2 = 3, remainder 0
 3 // 2 = 1, remainder 1
 1 // 2 = 0, remainder 1
Binary: 1101

The same method works for any base: divide by 8 for octal or by 16 for hexadecimal, and use the letters A to F for the remainders 10 to 15. To convert binary text back to a number, see binary to decimal.

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