如何在VB.net中实现数组的哈希函数 [英] How to implement a hash function for an array in VB.net

查看:200
本文介绍了如何在VB.net中实现数组的哈希函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#中用于从数组创建哈希值的经典函数看起来像这样或类似:

The classic function in C# to create a hash value from an array looks like this or similar:

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;
        }
    }

但是由于未选中在VB.Net中不可用,因此当溢出时我会很快收到异常。

我以为我可以使用位移来解决它,但是在VB中它只有算术而不是圆形所以每一个被移出的位都会被丢弃。



虽然我无法相信这在VB中从未解决过,但我的google foo让我失望。



获取哈希值的标准解决方案是什么? VB中的数组?

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?

推荐答案

你难道不能将哈希声明为 Int64 并清除上半部分需要?
Couldn't you just declare hash as Int64 and clear the upper part when needed?


为了将来参考,这就是我的解决方案的样子:
For future reference, this is how my solution looks like:
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

有一些改善性能的空间,溢出只需要每6次迭代处理一次,例如

There is some room for improving performance, the overflow only needs to be handled every 6 iterations for example


这篇关于如何在VB.net中实现数组的哈希函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆