Part 02 / Topic 9 of 10
Number systems (brief)
Computers store everything as bits (0 or 1), so they count in binary (base 2). Octal (base 8) and hex (base 16) are short ways to write binary: one hex digit = 4 bits.
Real-world example: Web colours use hex: #FF5733 means red=255, green=87, blue=51.
print(bin(10), oct(10), hex(255)) # 0b1010 0o12 0xff
print(0b1010, 0o12, 0xFF) # 10 10 255
print(int("FF", 16)) # 255
print(f"{10:b} {255:x} {255:X}") # 1010 ff FF
| System | Base | Prefix | Function |
|---|---|---|---|
| Binary | 2 | 0b |
bin() |
| Octal | 8 | 0o |
oct() |
| Decimal | 10 | โ | int() |
| Hexadecimal | 16 | 0x |
hex() |
๐ Going deeper:
bin(),oct()andhex()return strings, not numbers.int("0xff", 16)also accepts the prefix, andint("ff", 0)fails because base0needs a prefix to guess the base.
Done here? The practice set for Part 2 โ 8 exercises with solutions โ is on the part page.