Skip to content

Instantly share code, notes, and snippets.

@vayam
Last active December 18, 2015 07:29
Show Gist options
  • Save vayam/5746665 to your computer and use it in GitHub Desktop.
Save vayam/5746665 to your computer and use it in GitHub Desktop.
fnv hash test

http://play.golang.org/p/Olj-v2jBeu

php implementation that works on both 32bit and 64bit

$hash_key = "pwnd";
$to_hash = "Naren";
$buf = str_split($hash_key.$to_hash);
$hash = 2166136261; #offset32
foreach ($buf as $chr)
{
    $hash ^= ord($chr);
    $hash += ($hash << 1) + ($hash << 4) + ($hash << 7) + ($hash << 8) + ($hash << 24);
    $hash = $hash & 0x0ffffffff;
}
$hash = $hash & 0x0ffffffff;
echo dechex($hash)."\n";

Golang has built in implementation which is kinda nice

package main

import "fmt"
import "hash/fnv"
import "io"

const HASH_KEY = "pwnd"

func fnvHash(s string) string {
  h := fnv.New32a()
	io.WriteString(h, HASH_KEY+s)
	hashString := fmt.Sprintf("%x", h.Sum(nil))
	return hashString
}

func main() {
	fmt.Println(fnvHash("Naren"))
}

c implementation

#include<stdio.h>

const unsigned OFFSET32_BASIS = 2166136261;
const unsigned FNV_PRIME = 16777619;

unsigned fnv1a_hash32(char *s)
{
  unsigned hash = OFFSET32_BASIS;
  while(*s) {
    hash = ( hash ^ *s ) * FNV_PRIME;
    s++;
  }
  return hash;
}

int main(void) {
  printf("%x\n",fnv1a_hash32("pwndNaren"));
  return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment