I have some code that I'm using in a standard C# application. I'm sharing the library in a silverlight project that doesn't allow unsafe code. I don't know much at all about unsafe/pointer logic/arethmetic and was wondering if someone could translate the following code snippet so that it will run without /unsafe. I don't care about the performance drop since the code won't be called often on the client. Thanks in advance for any assistance.
public static unsafe int GetStableHash(string name)
{
fixed (char* str = name)
{
char* chPtr = str;
int num = 352654597;
int num2 = num;
int* numPtr = (int*)chPtr;
for (int i = name.Length; i > 0; i -= 4)
{
num = (((num << 5) + num) + (num >> 27)) ^ numPtr[0];
if (i <= 2)
{
break;
}
num2 = (((num2 << 5) + num2) + (num2 >> 27)) ^ numPtr[1];
numPtr += 2;
}
return (num + (num2 * 1566083941));
}
}
@JeffMercado Thanks again for your time here guys. I appreciate it. I've tried your updated version and now I get the exception on line
num = (((num << 5) + num) + (num >> 27)) ^ BitConverter.ToInt32(bytes, j + 0);
The test code I'm using is
string[] tmp = new string[]
{
"Hello",
"Isn't that Æegis over there?",
"Isn't that something",
"11111111111",
"111",
"112"};
foreach (string s in tmp)
{
int one = GetStableHash(s);
int two = GetStableHashSafe(s);
System.Diagnostics.Debug.WriteLine(one + " : " + two + " == " + (one == two).ToString());
}