In []:
FNV (or Fowler-Noll-Vo is a non-cryptographic hash function.
Aside from code simplicity, this hash function is not particularly good at anything.
Python implementation
Below are self-contained implementations of the FNV hash function in Python. Feel free to grab one and copy-paste it into your projects.
FNV-1
This function reads a byte array and produces a U64 hash value.
In [2]:
def fnv1(buf: bytes) -> int: h = 14695981039346656037 for b in buf: h *= 1099511628211 h &= 0xFFFFFFFFFFFFFFFF # 64-bit mask h ^= b return h
In [3]:
fnv1(b"Hello world") fnv1(b"Hello wordl")
Out [3]:
13583674344491166159
Out [3]:
13583665548398140543
FNV-1a
This is the same as FNV-1, but the multiplication and XOR operations are swapped. This is done to improve avalanche effect.
In [4]:
def fnv1a(buf: bytes) -> int: h = 14695981039346656037 for b in buf: h ^= b h *= 1099511628211 h &= 0xFFFFFFFFFFFFFFFF # 64-bit mask return h
In [5]:
fnv1a(b"Hello world") fnv1a(b"Hello wordl")
Out [5]:
2815866345377719495
Out [5]:
2823738848634196455
References and useful links
- FNV Hash on Wikipedia
- SMhasher results for FNV-1a