Click here to Skip to main content
15,890,579 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
The classic function in C# to create a hash value from an array looks like this or similar:
C#
public int GetHashCode(T[] array)
    {
        unchecked
        {
            if (array == null)
            {
                return 0;
            }
            int hash = 17;
            foreach (T item in array)
            {
                hash = hash * 31 + item.GetHashCode;
            }
            return hash;
        }
    }
But since unchecked is not available in VB.Net I will quickly get an exception when it overflows.
I thought I could solve it using bitshifting, but in VB its only arithmetic and not circular so every bit that is shifted out is dropped.

And while I can't believe this has never been solved in VB my google foo is failing me.

What is the standard solution for getting a hash value for an array in VB?
Posted
Updated 19-May-14 4:49am
v2

Couldn't you just declare hash as Int64 and clear the upper part when needed?
 
Share this answer
 
Comments
Jörgen Andersson 19-May-14 12:27pm    
That would mean that the first items influence on the hash would be shifted out after just seven more items added.
This is the reason I wanted to use a circular bitshift, but that is also not available in VB.
CPallini 19-May-14 12:33pm    
However that's exactly what happens in the C# code, right?
Jörgen Andersson 19-May-14 12:37pm    
No, that's why you want the 'Unchecked' operator, it overflows without an exception.
CPallini 19-May-14 15:43pm    
Well, 'overflows without an exceptions' doesn't prevent it to discard the bits.
Jörgen Andersson 19-May-14 16:33pm    
Dammit, you're right.
That means I've tried to fix something that wasn't as broken as I thought. Either that, or the implementation is faulty.
For future reference, this is how my solution looks like:
VB
Public Overrides Function GetHashCode() As Integer
     Dim hash As Int64 = 19
     For Each Item As T In Me
         hash = hash * 31 + Item.GetHashCode
         hash = ((hash << 32) >> 32) + hash >> 32
     Next
     hash = ((hash << 32) >> 32)
     Return CInt(hash)
 End Function
There is some room for improving performance, the overflow only needs to be handled every 6 iterations for example
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900