Created
December 28, 2023 13:06
-
-
Save riicchhaarrd/4e502811a52fa27a79340a5146bef208 to your computer and use it in GitHub Desktop.
Fowler–Noll–Vo 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
// https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function | |
#include <stdint.h> | |
#include <stdio.h> | |
#include <assert.h> | |
typedef uint64_t u64; | |
typedef uint32_t u32; | |
u32 fnv1a_32(const char *str) | |
{ | |
u32 prime = 0x01000193; | |
u32 offset = 0x811c9dc5; | |
u32 hash = offset; | |
while(*str) | |
{ | |
hash ^= *str; | |
hash *= prime; | |
++str; | |
} | |
return hash; | |
} | |
u64 fnv1a_64(const char *str) | |
{ | |
u64 prime = 0x00000100000001B3; | |
u64 offset = 0xcbf29ce484222325; | |
u64 hash = offset; | |
while(*str) | |
{ | |
hash ^= *str; | |
hash *= prime; | |
++str; | |
} | |
return hash; | |
} | |
void print_hex_string(char *data, size_t n) | |
{ | |
for(size_t i = 0; i < n; ++i) | |
{ | |
printf("%02X", data[n - i - 1] & 0xff); | |
} | |
} | |
int main(int argc, char **argv) | |
{ | |
assert(argc >= 2); | |
u64 h = fnv1a_64(argv[1]); | |
printf("%lld 0x%x\n", h, h); | |
printf("hex: %d bytes ", sizeof(h)); | |
print_hex_string((char*)&h, sizeof(h)); | |
printf("\n"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment