xxHash convert resulting in hash too long

3.1k Views Asked by At

I'm using xxHash for C# to hash a value for consistency. ComputeHash returns a byte[], but I need to store the results in a long.

I'm able to convert the results into an int32 using the BitConverter. Here is what I've tried:

var xxHash = new System.Data.HashFunction.xxHash();
byte[] hashedValue = xxHash.ComputeHash(Encoding.UTF8.GetBytes(valueItem));
long value = BitConverter.ToInt64(hashedValue, 0);

When I use int this works fine, but when I change to ToInt64 it fails.

Here's the exception I get:

Destination array is not long enough to copy all the items in the collection. Check array index and length.

3

There are 3 best solutions below

0
On BEST ANSWER

Adding a new answer because current implementation of xxHash from Brandon Dahler uses a hashing factory where you initialize the factory with a configuration containing hashsize and seed:

using System.Data.HashFunction.xxHash;

//can also set seed here, (ulong) Seed=234567
xxHashConfig config = new xxHashConfig() { HashSizeInBits = 64 };
var factory = xxHashFactory.Instance.Create(config);
byte[] hashedValue = factory.ComputeHash(Encoding.UTF8.GetBytes(valueItem)).Hash;
1
On

BitConverter.ToInt64 expects hashedValue to have 8 bytes (= 64bits). You could manually extend, and then pass it.

3
On

When you construct your xxHash object, you need to supply a hashsize:

var hasher = new xxHash(32);

valid hash sizes are 32 and 64.

See https://github.com/brandondahler/Data.HashFunction/blob/master/src/xxHash/xxHash.cs for the source.