Skip to content

Instantly share code, notes, and snippets.

@jmrnilsson
Last active May 9, 2020 05:43
Show Gist options
  • Save jmrnilsson/902f2105f46b23838e7c20641ed70155 to your computer and use it in GitHub Desktop.
Save jmrnilsson/902f2105f46b23838e7c20641ed70155 to your computer and use it in GitHub Desktop.
Fowler–Noll–Vo 1 A (FNV1) in 32 bit and 64 bit variants
using System;
using System.Text;
namespace Hashing
{
public static class FowlerNollVo
{
public static string ToFnv1aHashInt64(this string text)
{
string Fnv1a(byte[] bytes_)
{
const ulong offset = 14695981039346656037;
const ulong prime = 1099511628211;
ulong hash = offset;
for (var i = 0; i < bytes_.Length; i++)
{
unchecked
{
hash ^= bytes_[i];
hash *= prime;
}
}
return Convert.ToBase64String(BitConverter.GetBytes(hash));
}
byte[] bytes = Encoding.UTF8.GetBytes(text);
return Fnv1a(bytes);
}
public static string ToFnv1aHashInt32(this string text)
{
string Fnv1a(byte[] bytes_)
{
const uint offset = 0x811C9DC5;
const uint prime = 0x01000193;
uint hash = offset;
for (var i = 0; i < bytes_.Length; i++)
{
unchecked
{
hash ^= bytes_[i];
hash *= prime;
}
}
// return BitConverter.ToInt64(bytes_, 0);
return Convert.ToBase64String(BitConverter.GetBytes(hash));
}
byte[] bytes = Encoding.UTF8.GetBytes(text);
return Fnv1a(bytes);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment