背景
net旧项目使用32位生成的HashCode,存储到数据库中。迁移到64位上,就需要对HashCode做兼容处理。
解决方案
1:进程池配置支持32位程序。
2:对Hashcode做兼容处理,【推荐】。
兼容实现
static void Main(string[] args) { string test = "hello"; //-327419862 64位下 //-695839 32位下 int bit = test.GetHashCode(); int hashCode = CompatibleHash("hello"); } /// <summary> /// 64位环境下,生成兼容32位的hashCode。 /// </summary> /// <param name="str"></param> /// <returns></returns> public static unsafe int CompatibleHash(string str) { fixed (char* charPtr = new String(str.ToCharArray())) { int hashCode = (5381 << 16) + 5381; int numeric = hashCode; int* intPtr = (int*)charPtr; for (int i = str.Length; i > 0; i -= 4) { hashCode = ((hashCode << 5) + hashCode + (hashCode >> 27)) ^ intPtr[0]; if (i <= 2) break; numeric = ((numeric << 5) + numeric + (numeric >> 27)) ^ intPtr[1]; intPtr += 2; } return hashCode + numeric * 1566083941; } }