Powers of Two
Computers count in binary, so the numbers 1, 2, 4, 8, 16, 32, … show up everywhere in software: memory sizes, texture dimensions, colour depths, hash table capacities, the limits of integer types. Knowing the first few powers of two by heart is one of the most useful bits of math a programmer can carry.
The table worth memorising
| Where you meet it | ||
|---|---|---|
| 0 | 1 | |
| 1 | 2 | a single bit: 0 or 1 |
| 4 | 16 | one hex digit (0–F) |
| 8 | 256 | values in one byte (0–255) |
| 10 | 1,024 | 1 KiB |
| 16 | 65,536 | values in 2 bytes; port numbers go up to 65,535 |
| 20 | 1,048,576 | 1 MiB |
| 24 | 16,777,216 | colours in 24-bit RGB |
| 30 | 1,073,741,824 | 1 GiB |
| 31 | 2,147,483,648 | just past the largest signed 32-bit int |
| 32 | 4,294,967,296 | values in 32 bits (IPv4 addresses) |
| 64 | about | values in 64 bits |
A handy bridge: . So (a million), (a billion), and (a trillion).
Why bits give values
Each bit has 2 choices, and choices multiply. With 3 bits: patterns, from 000 to 111, which is 0 to 7. In general, bits store different values, and an unsigned -bit integer runs from 0 to .
for bits in [1, 3, 8, 16, 32]:
count = 2 ** bits
print(f"{bits:2d} bits: {count:>13,} values, unsigned max {count - 1:,}")
print("signed 32-bit range:", -2**31, "to", 2**31 - 1) 1 bits: 2 values, unsigned max 1
3 bits: 8 values, unsigned max 7
8 bits: 256 values, unsigned max 255
16 bits: 65,536 values, unsigned max 65,535
32 bits: 4,294,967,296 values, unsigned max 4,294,967,295
signed 32-bit range: -2147483648 to 2147483647
A signed type spends one bit on the sign, so it covers to . More in Binary and Hexadecimal and Integer Overflow.
KiB vs KB
Storage has two families of units, and mixing them up is a famous source of confusion:
| Binary (IEC) | Value | Decimal (SI) | Value |
|---|---|---|---|
| 1 KiB (kibibyte) | bytes | 1 kB (kilobyte) | bytes |
| 1 MiB | bytes | 1 MB | bytes |
| 1 GiB | bytes | 1 GB | bytes |
| 1 TiB | bytes | 1 TB | bytes |
Disk makers sell in decimal units, operating systems often report in binary ones. That is why a "1 TB" drive shows up as about 931 "GB" (really GiB):
drive = 10 ** 12 # 1 TB as sold
gib = drive / 2 ** 30
tib = drive / 2 ** 40
print(f"1 TB = {gib:.1f} GiB = {tib:.3f} TiB")
limit = 16 * 2 ** 10 # a 16 KiB size limit
print("16 KiB =", limit, "bytes")1 TB = 931.3 GiB = 0.909 TiB
16 KiB = 16384 bytes
Powers of two in code
Programs love powers of two because they line up with binary:
- Shifts:
1 << nequals , andx << 3multiplies by 8. Shifting is how is built in C, Rust and Java. - Power-of-two check: a power of two has exactly one 1-bit, so
n & (n - 1) == 0(for ) tests it. - Cheap modulo: if
sizeis a power of two,i % sizeequalsi & (size - 1). Hash tables and ring buffers use capacities like 16, 32, 64 for this reason. - Textures: GPUs have long preferred textures with power-of-two sides (, ), because mipmaps halve each side down to .
def is_pow2(n):
return n > 0 and n & (n - 1) == 0
print([n for n in range(1, 70) if is_pow2(n)])
print("1 << 10 =", 1 << 10)
print("37 % 16 =", 37 % 16, " 37 & 15 =", 37 & 15)
# Mipmap chain of a 1024 x 1024 texture
side, levels = 1024, []
while side >= 1:
levels.append(side)
side //= 2
print(len(levels), "levels:", levels)[1, 2, 4, 8, 16, 32, 64]
1 << 10 = 1024
37 % 16 = 5 37 & 15 = 5
11 levels: [1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1]
The 11 levels are down to . Counting how many times you can halve is exactly a logarithm, the topic of the next section.
Tip: To find the next power of two at or above in Python, use
1 << (n - 1).bit_length()(for ). Allocators and dynamic arrays grow their buffers this way.
Exercises
Exercise 1: Recall
Without a calculator: , , , and .
Answer
64, 512, 4096, 65,536.
Solution
Double from a value you know: . , so and . .
Exercise 2: How many bits?
How many bits do you need to give every one of 1000 users a different ID? And for 5000 users?
Answer
10 bits for 1000 users; 13 bits for 5000 users.
Solution
You need the smallest with . , so 10 bits. , so 13 bits.
for users in [1000, 5000]:
n = 0
while 2 ** n < users:
n += 1
print(users, "users ->", n, "bits")1000 users -> 10 bits
5000 users -> 13 bits
Exercise 3: Texture memory
An RGBA texture uses 4 bytes per pixel. How many MiB does a texture take?
Answer
16 MiB.
Solution
Exercise 4: Next power of two
Write next_pow2(n) that returns the smallest power of two that is , using a loop (no bit tricks). Test it on 1, 5, 64 and 1000.
Answer
1, 8, 64, 1024.
Solution
Start at 1 and double until you reach .
def next_pow2(n):
p = 1
while p < n:
p *= 2
return p
print([next_pow2(n) for n in [1, 5, 64, 1000]])
print([1 << (n - 1).bit_length() for n in [1, 5, 64, 1000]])[1, 8, 64, 1024]
[1, 8, 64, 1024]
The second line checks the answer with the bit-length trick from the tip above.
Test yourself
How many different values can one byte (8 bits) hold?
- 8
- 255
- 256
- 1024
How many bytes are in 1 MiB?
- 1,000,000
- 1,048,576
- 1,024
- 1,000,024
Which Python expression is True exactly when the positive integer n is a power of two?
- n % 2 == 0
- n & (n - 1) == 0
- n ** 2 == n
- n >> 1 == 0