【发布时间】:2014-10-27 22:16:03
【问题描述】:
所以我正在为这个算法制作一个哈希码函数: 对于每个字符将当前位向左旋转三位 添加每个字符的值, xor 与当前的结果 这是我到目前为止的代码:
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);
标签: c algorithm hash bit-manipulation bitwise-operators