.NetCore中获取持久化哈希值

.NET Core中每次程序启动通过系统内置的 GetHashCode 获取到的都不同,可通过下面的算法获取到的哈希值持久化不变。

复制代码
var str = "1";
            Console.WriteLine(str.GetHashCode());
            var str2 = "1";
            Console.WriteLine(str2.GetHashCode());
            Console.WriteLine("-------------------------------");

            var str3 = "2";
            Console.WriteLine(str3.GetExtHashCode());
            var str4 = "2";
            Console.WriteLine(str4.GetExtHashCode());

            Console.ReadKey();
复制代码

 

复制代码
   public static class HashExtends
    {
        public static int GetExtHashCode(this string str)
        {
            unchecked
            {
                int hash1 = (5381 << 16) + 5381;
                int hash2 = hash1;
                for (int i = 0; i < str.Length; i += 2)
                {
                    hash1 = ((hash1 << 5) + hash1) ^ str[i];
                    if (i == str.Length - 1)
                        break;
                    hash2 = ((hash2 << 5) + hash2) ^ str[i + 1];
                }
                return hash1 + (hash2 * 1566083941);
            }
        }
    }
复制代码

 

支持作者原创来源:https://codedefault.com/p/why-is-string-gethashcode-method-get-difference-hash-code-when-restart-aspnet-core-application

 

posted @   吉姆杨  阅读(194)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示