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