Skip to content

Instantly share code, notes, and snippets.

@devhawk
Last active December 14, 2019 00:17
Show Gist options
  • Select an option

  • Save devhawk/b05ef00fc2ce6bbd1382fe049256075c to your computer and use it in GitHub Desktop.

Select an option

Save devhawk/b05ef00fc2ce6bbd1382fe049256075c to your computer and use it in GitHub Desktop.
Lightweight implementation of 32 & 64 bit FNV Hash algorithms
using System;
namespace DevHawk
{
public class FNVHash
{
public const uint Prime32 = 16777619;
public const uint Offset32 = 2166136261;
public const ulong Prime64 = 1099511628211;
public const ulong Offset64 = 14695981039346656037;
public static uint Hash32(byte value, uint hash = Offset32) => (hash * Prime32) ^ value;
public static uint Hash32(Span<byte> span, uint hash = Offset32)
{
for (var i = 0; i < span.Length; i++)
{
hash = Hash32(span[i], hash);
}
return hash;
}
public static uint Hash32Alt(byte value, uint hash = Offset32) => hash = (hash ^ value) * Prime32;
public static uint Hash32Alt(Span<byte> span, uint hash = Offset32)
{
for (var i = 0; i < span.Length; i++)
{
hash = Hash32Alt(span[i], hash);
}
return hash;
}
public static ulong Hash64(byte value, ulong hash = Offset64) => (hash * Prime64) ^ value;
public static ulong Hash64(Span<byte> span, ulong hash = Offset64)
{
for (var i = 0; i < span.Length; i++)
{
hash = Hash64(span[i], hash);
}
return hash;
}
public static ulong Hash64Alt(byte value, ulong hash = Offset64) => (hash ^ value) * Prime64;
public static ulong Hash64Alt(Span<byte> span, ulong hash = Offset64)
{
for (var i = 0; i < span.Length; i++)
{
hash = Hash64Alt(span[i], hash);
}
return hash;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment