c - 使用按位运算的 C 中的哈希码算法

标签 c algorithm hash bit-manipulation bitwise-operators

所以我正在为这个算法制作一个哈希码函数: 对于每个字符,将当前位向左旋转三位 添加每个字符的值, 将结果与当前异或 这是我到目前为止的代码:

unsigned int hash_function(const char *k){   
    unsigned int current = 0;   
    unsigned int rot = 0;  
    int i = 0;  
    int r = 0;  
    for(i = 0; i < strlen(k); i++){  
        for(r = 0; r < 3; r++){  
            rot = ((rot & 1 (1 << 31)) >> 31 | (rot << 1);  
        }  
        rot += k[i];  
        current ^= rot;  
        rot = current;  
    }  
    return current;  
}

算法应该给出的一些例子 “给我”= 477003, “避难所”= 41540041 然而,这个算法并没有给我正确的结果。我相当确定我正在使用正确的旋转操作,然后我按原样遵循算法。我想知道是否有人能指出我正确的方向。 谢谢,希望我正确地格式化了这个问题

最佳答案

我想你是想把 rot = ((rot & (1 << 31)) >> 31) | (rot << 1); .但是循环是不必要的——使用 rot = ((rot & (7 << 29)) >> 29) | (rot << 3);相反。

这应该有效:

unsigned int hash_function(const char *k){   
    unsigned int current = 0;   
    unsigned int rot = 0;  
    int i = 0;  
    for (i = 0; i < strlen(k); i++){  
        rot = ((rot & (7 << 29)) >> 29) | (rot << 3);  
        rot += k[i];  
        current ^= rot;  
        rot = current;  
    }  
    return current;  
}

关于c - 使用按位运算的 C 中的哈希码算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26597792/

相关文章:

c++ - 使用 CryptSignHash 获取 PKCS#7 签名

C For 循环比较使用函数不等待

python - 对于给定的 fp 精度,检查 Python 中的数字是否有理数

algorithm - N 维平面中某个点的唯一标识哈希码是什么?

algorithm - 将点分成最大距离的集合

arrays - 如何在 Perl 中正确传递引用和嵌套引用

java - 验证期间计算的签名 PDF 内容摘要与签名解密的摘要不同

C# 互操作 : Returning struct from unmanaged code with out parameter gives strange results

algorithm - 字符串的哈希算法

c++ - 如何访问RTCVideoRenderer的帧? (ios)