Sub topic 7
Building a better hash: polynomial hashing and FNV-1a
What this chapter assumes
You should be comfortable with Python, bytes, hexadecimal, XOR, masks, and the modulo operator. You should also know why a hash table needs a function that turns a key into a bucket index. The previous chapter showed that summing character codes fails because the sum ignores order. This chapter builds two simple replacements and shows where each one breaks.
Both functions are non-cryptographic. They are fast and spread keys well for ordinary data. They offer no protection against an attacker who chooses the input.
Make position matter
A sum treats every byte the same. A better hash has to give each position a different influence on the result. The simplest way is to multiply the running value before adding the next byte.
That idea is the polynomial hash. For bytes b0, b1, ..., b(n-1) and a constant base:
h = b0 · base^(n-1) + b1 · base^(n-2) + ... + b(n-1)
You never compute the powers. Horner's rule evaluates the polynomial in one pass: start at 0, then for each byte compute h = h * base + byte.
Take "ab" and "ba" with base 31. The byte values are 97 and 98.
| Input | Calculation | Result |
|---|---|---|
| "ab" | 31 · 97 + 98 | 3105 |
| "ba" | 31 · 98 + 97 | 3135 |
The sum hash gives both strings 195. The polynomial hash separates them, because the first byte is multiplied once more than the last.
def poly_hash(data: bytes, base: int = 31, mod: int = 2**32) -> int:
h = 0
for b in data:
h = (h * base + b) % mod
return h
print(poly_hash(b"ab"), poly_hash(b"ba"))
print(poly_hash(b"\x00"), poly_hash(b"\x00\x00"), poly_hash(b""))The first line prints 3105 3135. The second prints 0 0 0, which shows the first weakness covered below.
Choosing the base and modulus
Python integers never overflow, so the % mod is a deliberate choice. In C or Rust the same step happens implicitly when a 32-bit integer wraps. The modulus keeps the value a fixed size, and the base controls how fast earlier bytes get pushed upward.
- Use an odd base. With a power-of-two modulus, an even base shifts bits left. Base 2 pushes the first byte completely out of a 32-bit value after 32 characters, so it stops affecting the hash.
- Do not use 256 with mod 2^32. Only the last four bytes would matter, because 256^4 = 2^32.
- Small primes such as 31 or 33 are conventional. They are cheap to multiply and work acceptably on text. Nothing makes 31 magical.
Leading zero bytes vanish
Because h starts at 0 and 0 times anything is 0, the inputs b"", b"\x00" and b"\x00\x00" all hash to 0. Text rarely starts with NUL bytes, but binary data does. A good hash should not treat "nothing" and "some zeros" as the same thing. FNV fixes this with a nonzero starting value.
FNV-1a
FNV (Fowler–Noll–Vo) is a short, fast, non-cryptographic hash. The 1a variant processes each byte in two steps:
- XOR the byte into the hash.
- Multiply the hash by a fixed prime, keeping only 32 bits.
The starting value is the offset basis 0x811C9DC5, which is nonzero by design. The 32-bit prime is 0x01000193.
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
# Published test vectors for FNV-1a 32-bit
assert fnv1a_32(b"") == 0x811C9DC5
assert fnv1a_32(b"a") == 0xE40C292C
assert fnv1a_32(b"foobar") == 0xBF9CF968
print(hex(fnv1a_32(b"hello")))
print(fnv1a_32(b"hello") % 16)The assertions are worth keeping. A hash implementation can be wrong in ways that still look random, and known test vectors are the only reliable check. The final line is the bucket-mapping step from earlier: the modulo turns a 32-bit value into an index from 0 to 15.
The 64-bit version uses the offset basis 0xcbf29ce484222325, the prime 0x100000001b3, and a mask of 2**64 - 1. Use it when you want fewer collisions or a larger table.
Why XOR first
The older FNV-1 multiplies first and then XORs. FNV-1a swaps the order. The swap improves mixing: the new byte is XORed in, and the multiplication then spreads its influence into higher bits. In FNV-1 the last byte is XORed after the final multiplication, so it only touches the low bits. Prefer 1a.
Why it works
- The nonzero offset basis means an empty input and a run of zero bytes give different results.
- The prime is odd, so multiplying by it never discards information.
- The multiply carries each bit's influence toward higher positions, which partly produces the avalanche effect covered in the next chapter.
Gotcha: low bits and power-of-two bucket counts
Look at what multiplication, addition and XOR do modulo 2^k. The lowest k bits of the result depend only on the lowest k bits of the inputs. Carries only travel upward.
FNV-1a is built from exactly those operations. If your table has 16 buckets and you take h % 16, you keep only the low 4 bits of the hash. Those 4 bits are determined entirely by the low 4 bits of every input byte.
In ASCII, a is 0x61 and A is 0x41. They differ only in bit 5, which lies outside the low nibble. So case variants of a word always share a bucket:
def fnv1a_32(data: bytes) -> int:
h = 0x811C9DC5
for byte in data:
h ^= byte
h = (h * 0x01000193) & 0xFFFFFFFF
return h
def fold(h: int) -> int:
return h ^ (h >> 16) # mix high bits into low bits
words = [b"hello", b"Hello", b"hELLO", b"HELLO"]
print([fnv1a_32(w) % 16 for w in words])
print([fold(fnv1a_32(w)) % 16 for w in words])The first line prints four identical numbers. This is guaranteed by the arithmetic, not by chance. The second line is usually different, because the fold brings the well-mixed upper bits down into the bucket index.
The same issue affects the polynomial hash with a power-of-two modulus: its low bits depend only on the low bits of the bytes.
Choosing between the two
| Property | Polynomial hash | FNV-1a |
|---|---|---|
| Per-byte work | one multiply, one add | one XOR, one multiply |
| Order sensitive | yes | yes |
| Leading zero bytes | lost with start value 0 | preserved by offset basis |
| Parameters to pick | base and modulus | none, fixed constants |
| Weak low bits | yes with power-of-two modulus | yes with power-of-two buckets |
| Suited to | rolling hashes, string search | small keys, short strings |
Polynomial hashing has one property FNV lacks. You can update it cheaply when a window slides along a string, by subtracting the outgoing byte's term and adding the incoming one. This is the basis of the Rabin–Karp search algorithm.
Limits of both designs
Neither function resists an adversary. The algorithms are public and the arithmetic is simple, so an attacker can construct many inputs that land in one bucket. Hash flooding and its defense are covered in a later chapter. Neither function is a cryptographic hash. Do not use them to check file integrity, sign data, or store passwords.
Both also process one byte at a time, which is slow for large inputs. Modern non-cryptographic hashes read 8 or more bytes per step. For short keys such as identifiers and words, FNV-1a is still a reasonable and easily audited choice.
Exercise
Using FNV-1a 32-bit with 8 buckets (h % 8), will the keys b"cat" and b"CAT" always share a bucket? Explain, and give one cheap change that avoids the problem.
Show answer
Yes. Lowercase and uppercase ASCII letters differ only in bit 5 (0x20). With 8 buckets only the low 3 bits of the hash are kept. Those bits depend only on the low 3 bits of each input byte, so the case difference never reaches them. Folding the high bits down before the modulo, for example (h ^ (h >> 16)) % 8, mixes in the well-mixed upper bits. Using a prime bucket count also works.
Exercise
Why does the polynomial hash in this chapter give b"" and b"\x00\x00" the same value, and how does FNV-1a avoid this?
Show answer
The polynomial hash starts at h = 0, and each zero byte computes 0 * base + 0 = 0, so the value never changes. FNV-1a starts at a nonzero offset basis and XORs and multiplies on every byte. A zero byte therefore still changes the state, and inputs of different lengths give different results.