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
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.
Enter a whole number: 2026 Binary: 0b11111101010 Octal: 0o3752 Hexadecimal: 0x7ea
How it works
- The prefixes
0b,0oand0xshow the base. You can type numbers with these prefixes in Python code too:0x7ea == 2026isTrue. - In hexadecimal, the digits after 9 are the letters a to f, for the values 10 to 15. 2026 = 7 × 256 + 14 × 16 + 10, so it is
7ea.
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:
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}")
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:
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)))
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.