FNV hashing in Mathematica

I recently needed to do Fowler/Noll/Vo hashing in Mathematica. I figured other people might have a need for this hash function as well, so here’s my Mathematica implementation:

(* FNV hash parameters: bit length, FNV prime, FNV offset *)
$FNVData = Append[#, Function[{bi, pr},
Fold[BitXor[Mod[pr #1, 2^bi], #2] &, 0,
ToCharacterCode["chongo /\\../\\"]]] @@ #] & /@ Transpose[{2^Range[5, 10],
2^(8 Quotient[2^Range[5, 10] + 5, 12]) + 2^8 +
Map[FromDigits[#, 16] &,
{"93", "B3", "3B", "63", "57", "8D"}]}];


FNV[dat_String, bi : _Integer : 32, shift : (0 | 1) : 1] := With[{k = IntegerExponent[bi, 2] - 4},
Fold[BitXor[Mod[$FNVData[[k, 2]] #1, 2^bi], #2] &,
shift $FNVData[[k, 3]], ToCharacterCode[dat]]] /;
32 <= bi <= 1024 && BitAnd[bi, bi - 1] == 0

I made sure to provide for both shift-1 and shift-0 versions in the implementation (though as mentioned on the FNV page, FNV-1 is what should be preferred). The FNV page has a few suggestions to extend FNV hashing to bit lengths that are not a power of two, but I did not bother with them. (Maybe somebody else can try!) It should not be too hard to modify the code to do FNV-1a hashing.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: