Created
September 14, 2022 11:10
-
-
Save ljmccarthy/907c4ac95d0ea8e693f0fbce2fcb8c7d to your computer and use it in GitHub Desktop.
FNV-1a hash function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Fowler–Noll–Vo hash function | |
# https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function | |
fnv_prime_32 = 2**24 + 2**8 + 0x93 | |
offset_basis_32 = 0x811c9dc5 | |
def fnv1a_hash_32(bs): | |
r = offset_basis_32 | |
for b in bs: | |
r = r ^ b | |
r = (r * fnv_prime_32) & 0xffffffff | |
return r | |
fnv_prime_64 = 2**40 + 2**8 + 0xb3 | |
offset_basis_64 = 0xcbf29ce484222325 | |
def fnv1a_hash_64(bs): | |
r = offset_basis_64 | |
for b in bs: | |
r = r ^ b | |
r = (r * fnv_prime_64) & 0xffffffffffffffff | |
return r | |
if __name__ == '__main__': | |
test_data = [ | |
b'hello, world!', | |
b'hello, world?', | |
b'The Queen is dead', | |
b'God save the King', | |
] | |
for datum in test_data: | |
print(hex(fnv1a_hash_32(datum)), datum.decode('ascii')) | |
for datum in test_data: | |
print(hex(fnv1a_hash_64(datum)), datum.decode('ascii')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment