Skip to content

Instantly share code, notes, and snippets.

@grodtron
Created February 29, 2012 04:19
Show Gist options
  • Save grodtron/1937678 to your computer and use it in GitHub Desktop.
Save grodtron/1937678 to your computer and use it in GitHub Desktop.
A test program that computes and displays the 64 bit NFW hash of an arbitrary c-string
/*
* This file contains an implementation of the
* 64-bit Fowler-Noll-Vo (FNV) hash function.
*
* More information can be found here;
* http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
*
* Gordon Bailey - Feb 28, 2012
*
*/
#include <inttypes.h>
#include <stdio.h>
// These values taken from http://isthe.com/chongo/tech/comp/fnv/#FNV-param
const uint64_t FNV_PRIME = 1099511628211;
const uint64_t OFFSET_BASIS = 14695981039346656037UL;
/* assumes a NULL terminated c-string as input */
uint64_t hash(char * string){
uint64_t hash = OFFSET_BASIS;
for(uint8_t * c = (uint8_t*)string; *c != 0; ++c){
hash ^= *c;
hash *= FNV_PRIME;
}
return hash;
}
/* assumes that outString has space allocated for 16 chars */
void getHex(uint64_t val, char * outString){
const char chars[] = "0123456789ABCDEF";
for(int i = 15; i >= 0; --i){
outString[i] = chars[val&15];
val >>= 4;
}
// add null terminator
outString[16] = '\0';
}
int main(int argc, const char *argv[])
{
// hold the outputted hex string
char hexString[17];
// copy entire argv into a single string (seperating elements with spaces)
char string[1024];
int j = 0;
for(int i = 1; i < argc; ++i){
for(const char * c = argv[i]; *c != '\0'; ++c){
if(j == 1023) break;
string[j] = *c;
++j;
}
if(j == 1023) break;
string[j] = ' ';
++j;
}
string[j] = '\0';
// get the hex string and print it.
uint64_t h = hash(string);
getHex(h, hexString);
printf("%s\n", string);
printf("%s\n", hexString);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment