Numbers and bits · 1 / 15 Theory

Number systems and bases

A number is a quantity; the base decides how it is written. In base 10 each position is worth a power of 10; in base 2 (binary), a power of 2; in base 16 (hexadecimal) a power of 16, with the digits 0-9 and A-F. Computers use binary and humans use hexadecimal as a compact form: each hexadecimal digit is exactly 4 bits.

print(bin(10), oct(64), hex(255))      # 0b1010 0o100 0xff
print(int("1010", 2), int("ff", 16))   # 10 255
print(0b1010 + 0x0F)                   # 25
print(format(5, "08b"))                # 00000101
print(f"{255:X} {255:o} {255:#b}")     # FF 377 0b11111111

def to_base(n, base):
    digits = "0123456789ABCDEF"
    if n == 0:
        return "0"
    result = ""
    while n > 0:
        result = digits[n % base] + result   # the remainder is the rightmost digit
        n //= base
    return result

print(to_base(255, 2), to_base(255, 16), to_base(100, 8))   # 11111111 FF 144
  • bin, oct and hex return text with a prefix (0b, 0o, 0x). int(text, base) does the opposite.
  • format(n, "08b") and f-strings with :b, :o, :x let you set the width and leading zeros.
  • To convert by hand: divide repeatedly by the base and the remainders, read from last to first, are the digits.
  • The literals 0b…, 0o… and 0x… can be written directly in code.

You practice it in Convert to base b.