我已经在几个论坛上问过这个问题,但没有任何好的解释,说明为什么上面的代码不能从C#转换为Visual Basic。如何在VB.NET中实现GetStableHash方法
代码实际上来自于这个论坛,用C#编写。 (the source)
static public int GetStableHash(string s)
{
uint hash = 0;
// if you care this can be done much faster with unsafe
// using fixed char* reinterpreted as a byte*
foreach (byte b in System.Text.Encoding.Unicode.GetBytes(s))
{
hash += b;
hash += (hash << 10);
hash ^= (hash >> 6);
}
// final avalanche
hash += (hash << 3);
hash ^= (hash >> 11);
hash += (hash << 15);
// helpfully we only want positive integer < MUST_BE_LESS_THAN
// so simple truncate cast is ok if not perfect
return (int)(hash % MUST_BE_LESS_THAN);
}
所以,代码应该是这样的,在VB.NET
Const MUST_BE_LESS_THAN As Integer = 100000000
Function GetStableHash(ByVal s As String) As Integer
Dim hash As UInteger = 0
For Each b as Byte In System.Text.Encoding.Unicode.GetBytes(s)
hash += b
hash += (hash << 10)
hash = hash Xor (hash >> 6)
Next
hash += (hash << 3)
hash = hash Xor (hash >> 11)
hash += (hash << 15)
Return Int(hash Mod MUST_BE_LESS_THAN)
End Function
这似乎是正确的,但它不工作。在VB.NET,存在在“散列+ =(散列< < 10)”的溢出
有没有办法改变VB.net中单个文件/文件的一部分溢出检查?类似于C#'unchecked'关键字? – CodesInChaos 2012-03-17 16:22:32
不,这个语言里没有关键字。不可能有,语言语法假定溢出检查。这就是为什么你不必强制将一个int分配给一个字节的原因。 – 2012-03-17 16:44:56