FNV Hash

Fowler-Noll-Vo Hash
Reading time: about 2 minutes
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

The following pages link here

Citation

If you find this work useful, please cite it as:
@article{yaltirakliwikifnvhash,
  title   = "FNV Hash",
  author  = "Yaltirakli, Gokberk",
  journal = "gkbrk.com",
  year    = "2024",
  url     = "https://www.gkbrk.com/wiki/fnv-hash/"
}
Not using BibTeX? Click here for more citation styles.
IEEE Citation
Gokberk Yaltirakli, "FNV Hash", December, 2024. [Online]. Available: https://www.gkbrk.com/wiki/fnv-hash/. [Accessed Dec. 30, 2024].
APA Style
Yaltirakli, G. (2024, December 30). FNV Hash. https://www.gkbrk.com/wiki/fnv-hash/
Bluebook Style
Gokberk Yaltirakli, FNV Hash, GKBRK.COM (Dec. 30, 2024), https://www.gkbrk.com/wiki/fnv-hash/

Comments

© 2024 Gokberk Yaltirakli