我需要将这段代码反向工程到C#中,关键是输出是完全相同的。对ord函数和"strHash % (1<<64)“部分有什么建议吗?
def easyHash(s):
"""
MDSD used the following hash algorithm to cal a first part of partition key
"""
strHash = 0
multiplier = 37
for c in s:
strHash = strHash * multiplier + ord(c)
#Only keep the last 64bit, since the mod base is 100
strHash = strHash % (1<<64)
return strHash % 100 #Assume eventVolume is Large发布于 2015-07-17 14:04:16
可能是这样的:
请注意,我使用的是ulong而不是long,因为我不希望在溢出之后出现负数(它们会扰乱计算)。我不需要做strHash = strHash % (1<<64),因为使用ulong是隐式的。
public static int EasyHash(string s)
{
ulong strHash = 0;
const int multiplier = 37;
for (int i = 0; i < s.Length; i++)
{
unchecked
{
strHash = (strHash * multiplier) + s[i];
}
}
return (int)(strHash % 100);
}unchecked关键字通常不是必需的,因为“通常”C#是在unchecked模式下编译的(所以不需要检查溢出),但是代码可以在checked模式下编译(有一个选项)。正如所写的,这段代码需要unchecked模式(因为它可能有溢出),所以我强制它使用unchecked关键字。
Python:https://ideone.com/RtNsh7
https://stackoverflow.com/questions/31477509
复制相似问题