Office中国论坛/Access中国论坛
标题:
【转载】.net中string所采用的散列函数
[打印本页]
作者:
faunus
时间:
2014-2-23 10:31
标题:
【转载】.net中string所采用的散列函数
using System;
namespace ConsoleApplication8
{
class Program
{
//项目属性对话框->配置属性->生成->允许不安全代码块->设为true
static public unsafe int DotNetHash(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;
}
}
static void Main(string[] args)
{
string test = "test it!";
Console.WriteLine(test.GetHashCode());
Console.WriteLine(DotNetHash(test));
Console.ReadKey();
}
}
}
欢迎光临 Office中国论坛/Access中国论坛 (http://www.office-cn.net/)
Powered by Discuz! X3.3