如何将这个Python代码翻译成C#?

2024-09-26 18:18:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要将这段代码逆向工程到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

Tags: the函数代码ltisdef工程建议
1条回答
网友
1楼 · 发布于 2024-09-26 18:18:56

可能是这样的:

请注意,我使用的是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关键字,因为“normaly”C#是在unchecked模式下编译的(因此不检查溢出),但是代码可以在checked模式下编译(有一个选项)。正如所写的,这段代码需要unchecked模式(因为它可能有溢出),所以我用unchecked关键字强制它。你知道吗

Python:https://ideone.com/RtNsh7

C#:https://ideone.com/0U2Uyd

相关问题 更多 >

    热门问题