Sub topic 7
Building a better hash: polynomial hashing and FNV-1a
This chapter assumes you know Python, hexadecimal, XOR, masks, and the modulo operator. You should also know why a hash table needs a function that spreads keys evenly. The previous chapter showed that summing character codes puts every anagram in the same bucket. Here you build two hashes that fix this.
Make position matter
The sum hash fails because addition ignores order. A fix must make each byte's contribution depend on where the byte sits. A polynomial hash does this by multiplying the running value by a constant base before adding each new byte:
def sum_hash(s, buckets):
return sum(s.encode()) % buckets
def poly_hash(s, buckets, base=31):
h = 0
for b in s.encode():
h = (h * base + b) % (2**32)
return h % buckets
anagrams = ["listen", "silent", "enlist", "tinsel", "inlets"]
print([sum_hash(w, 16) for w in anagrams])
print([poly_hash(w, 16) for w in anagrams])The first line prints 15 five times, because all five words have the same byte total (655). In the second line, the first byte is multiplied by base once for every byte after it. Swapping two letters therefore changes the result.
Mathematically, the hash of bytes b0, b1, ..., bn is b0·base^n + b1·base^(n-1) + ... + bn, taken modulo 2^32. Programmers often choose a small odd prime such as 31 for base. Using % (2**32) keeps the value in 32 bits, the way a fixed-width integer in C or Java would.
FNV-1a
FNV-1a (Fowler–Noll–Vo) is a short hash that mixes bits more aggressively. For each byte it XORs the byte into the state, then multiplies by a large prime:
def fnv1a_32(data: bytes) -> int:
h = 0x811C9DC5 # FNV offset basis
for byte in data:
h ^= byte
h = (h * 0x01000193) & 0xFFFFFFFF # FNV prime, keep 32 bits
return h
print(hex(fnv1a_32(b"hello")))
print(fnv1a_32(b"hello") % 16)The loop body has two steps:
- XOR changes the low bits of the state using the new byte.
- Multiplication by the prime spreads those changes into higher bits. The mask
& 0xFFFFFFFFdiscards overflow, so the value stays 32-bit.
The order matters. The older FNV-1 variant multiplies first and then XORs. FNV-1a, with XOR first, is generally reported to spread bits slightly better for short keys, so it is the usual choice.
Common errors
- Forgetting to mask. Python integers never overflow, so without
& 0xFFFFFFFFthe state grows without bound and your results will not match other FNV implementations. - Hashing
strinstead ofbytes. Encode the string first. Use the same encoding everywhere, or equal text will hash differently. - Using a power-of-two
basesuch as 32. This shifts bits and loses mixing, so early bytes soon disappear. - Treating these hashes as secure. They are fast and easy to reverse, and an attacker can build inputs that collide on purpose. Later chapters cover that.
Exercise
Explain why poly_hash("ab", 16) and poly_hash("ba", 16) can differ, while sum_hash("ab", 16) and sum_hash("ba", 16) never do.
Show answer
The sum hash adds the byte values, and addition does not depend on order, so both strings give the same total. The polynomial hash multiplies the running value by base before each new byte, so each byte's weight depends on its position. Swapping "ab" to "ba" changes the weights and usually the result.