Skip to content

Commit 3febb5c

Browse files
authored
Merge pull request #42 from Valdas3/master
#37: add Fowler–Noll–Vo hash function with tests
2 parents 84db931 + 5e8c482 commit 3febb5c

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
using System.Text;
2+
using Xunit;
3+
4+
namespace Algorithms.Tests.FowlerNollVoHashTests
5+
{
6+
// tests taken from http://www.isthe.com/chongo/src/fnv/test_fnv.c
7+
public class FowlerNollVoHashTests
8+
{
9+
[Theory]
10+
[InlineData("", 0x811c9dc5)]
11+
[InlineData("a", 0x050c5d7e)]
12+
[InlineData("b", 0x050c5d7d)]
13+
[InlineData("foo", 0x408f5e13)]
14+
[InlineData("foob", 0xb4b1178b)]
15+
[InlineData("fooba", 0xfdc80fb0)]
16+
[InlineData("foobar", 0x31f0b262)]
17+
[InlineData("http://en.wikipedia.org/wiki/Fowler_Noll_Vo_hash", 0x025dfe59)]
18+
public void Test(string input, uint expected)
19+
{
20+
var bytes = Encoding.UTF8.GetBytes(input);
21+
Assert.Equal(expected, FowlerNollVoHash.FowlerNollVoHash.Hash(bytes));
22+
}
23+
}
24+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
namespace Algorithms.FowlerNollVoHash
2+
{
3+
public static class FowlerNollVoHash
4+
{
5+
private static uint _fnvPrime = 16777619;
6+
private static uint _fnvOffset = 2166136261;
7+
// FNV-1 hash variant for 32-bit hash
8+
public static uint Hash(byte[] data)
9+
{
10+
if (data == null)
11+
{
12+
return 0;
13+
}
14+
var hash = _fnvOffset;
15+
foreach (var b in data)
16+
{
17+
hash = hash * _fnvPrime;
18+
hash = hash ^ b;
19+
}
20+
21+
return hash;
22+
}
23+
}
24+
}

0 commit comments

Comments
 (0)