Maths for Programmers and Olympiads
Lesson 1 / 15
Filbek
Number systems: binary and hexadecimal
Decimal, binary, hexadecimal; converting between them; colour codes
Chapter 1. Mathematical thinking
20 minutes
Python
4 questions
We count in the decimal system — 10 digits (0–9), because we have 10 fingers. A computer works in binary — only 0 and 1 (current on / off).
Place value
Decimal 347 = 3·100 + 4·10 + 7·1. Binary 100101 works the same way, only the places are powers of 2:
| Place | 2⁵=32 | 2⁴=16 | 2³=8 | 2²=4 | 2¹=2 | 2⁰=1 |
|---|---|---|---|---|---|---|
| Digit | 1 | 0 | 0 | 1 | 0 | 1 |
32 + 4 + 1 = 37.
print(format(37, "b")) # decimal to binary
print(format(37, "08b")) # 8 digits (as a byte)
print(int("100101", 2)) # binary to decimal
# Output: 100101
# Output: 00100101
# Output: 37
Converting by hand: keep dividing by 2
Divide by 2, write down the remainders, then read them backwards:
def to_binary(n):
if n == 0:
return "0"
digits = ""
while n > 0:
digits = str(n % 2) + digits
n //= 2
return digits
print(to_binary(37), to_binary(8), to_binary(255))
# Output: 100101 1000 11111111
Hexadecimal (hex)
Binary is very long — so programmers use hexadecimal: 0–9 and A–F (A=10 … F=15). One hex digit is exactly 4 bits; two make a byte.
print(hex(255))
print(int("ff", 16))
# Output: 0xff
# Output: 255
Colours on web pages are written in hex: #FF8800 — red FF, green 88, blue 00:
colour = "#FF8800"
red, green, blue = (int(colour[i:i + 2], 16) for i in (1, 3, 5))
print(red, green, blue)
# Output: 255 136 0
Practice Python
Write onlikka(ikkilik_matn) yourself (without int(..., 2)): multiply each digit by its place value and add up:
37
255
0
input() data
Write code and press "Run". Loading Python takes a few seconds the first time.
Show solution
def onlikka(ikkilik):
natija = 0
for raqam in ikkilik:
natija = natija * 2 + int(raqam)
return natija
for s in ["100101", "11111111", "0"]:
print(onlikka(s))