基于位运算的C语言散列码算法
所以我为这个算法做了一个散列码函数: 对于每个字符,将当前位向左旋转三位 添加每个字符的值, 将结果与当前值异或 以下是我目前掌握的代码:基于位运算的C语言散列码算法,c,algorithm,hash,bit-manipulation,bitwise-operators,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++){
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;
}
unsigned int hash_函数(const char*k){
无符号整数电流=0;
无符号整数rot=0;
int i=0;
int r=0;
对于(i=0;i rot=(rot&1(1>31 |)(rot这最初只是一个评论,但事实证明这是你问题的答案
在这一行:
rot = ((rot & 1 (1 << 31)) >> 31 | (rot << 1);
去掉这两件事:
rot = (rot & (1 << 31)) >> 31 | (rot << 1);
我想你的意思是把它放在这里(rot不需要int r=0
。我对这个答案投了更高的票,因为它解决了让我好奇的问题——OP为什么使用内部循环?非常感谢,我没有意识到你可以不用循环就这样做。这实际上是我做的一个复制粘贴错误,我正在使用一个检测错误的编译器。但无论如何,非常感谢感谢捐款
rot = (rot & (1 << 31)) >> 31 | (rot << 1);
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;
}