<分区>
我想为字符串生成一个整数哈希码,它将永远保持不变;即相同的字符串应该总是产生相同的哈希码。
散列不必是加密安全的,它不会用于密码或敏感数据。
我的第一次尝试是使用 .net 框架的 string.GetHashCode() 函数。 然而,在阅读资料后,我发现了以下评论:
// We want to ensure we can change our hash function daily. // This is perfectly fine as long as you don't persist the // value from GetHashCode to disk or count on String A // hashing before string B. Those are bugs in your code. hash1 ^= ThisAssembly.DailyBuildNumber;
这似乎表明哈希码不会保持不变。
如果是这样,框架是否有另一种方法来生成可重复的哈希码?还是 GetHashCode 中的代码是实现我自己的代码的合理起点?
我正在寻找尽可能轻便和快速的东西。
我找到了 System.Security.Cryptography.MD5 ,但对于一个简单的 int32 哈希码来说,这似乎有点过分了,我担心开销。至少它需要从字符串到字节数组的转换,从字节数组到 int 的转换,或者为每个散列创建一个新的 MD5()
对象,或者管理一些静态共享 MD5 对象().