Skip to content

Instantly share code, notes, and snippets.

@SteveBate
Last active October 6, 2015 09:49
Show Gist options
  • Save SteveBate/b99b1a02eca5762b90b1 to your computer and use it in GitHub Desktop.
Save SteveBate/b99b1a02eca5762b90b1 to your computer and use it in GitHub Desktop.
FNV-1 hashing function - an implementation in Go that matches the output of using the builtin fnv package
package main
import (
"fmt"
"hash/fnv"
)
func main() {
// the data to be hashed
data := []byte("Hello world")
// the Go in-built FNV hashing function
hash := fnv.New64()
hash.Write(data)
x := hash.Sum64()
fmt.Println(x)
// my implementation based on the pseudocode on wikipedia (see: https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function)
const FNVPrimeOffset uint64 = 14695981039346656037
const FNVPrimeValue uint64 = 1099511628211
var h uint64 = FNVPrimeOffset
for _, b := range data {
h = h * FNVPrimeValue
h = h ^ uint64(b)
}
fmt.Println(h)
// interestingly a supposedly superior distribution of hashes is achieved by changing the order of two lines.
// This is known as the FNV-1a hash algorithm
const FNVPrimeOffset uint64 = 14695981039346656037
const FNVPrimeValue uint64 = 1099511628211
var h uint64 = FNVPrimeOffset
for _, b := range data {
h = h ^ uint64(b)
h = h * FNVPrimeValue
}
fmt.Println(h)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment