【问题标题】:Algorithm for hash code in C using bitwise operations使用按位运算的 C 中哈希码算法
【发布时间】: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 &amp; (1 &lt;&lt; 31)) &gt;&gt; 31) | (rot &lt;&lt; 1); 。但循环是不必要的——改用rot = ((rot &amp; (7 &lt;&lt; 29)) &gt;&gt; 29) | (rot &lt;&lt; 3);

标签: c algorithm hash bit-manipulation bitwise-operators


【解决方案1】:

我认为您的意思是输入rot = ((rot &amp; (1 &lt;&lt; 31)) &gt;&gt; 31) | (rot &lt;&lt; 1);。但循环是不必要的——改用rot = ((rot &amp; (7 &lt;&lt; 29)) &gt;&gt; 29) | (rot &lt;&lt; 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;  
}

【讨论】:

  • 不需要int r = 0。我赞成这个答案,因为它解决了让我好奇的问题 - 为什么 OP 使用内部循环?
  • 非常感谢,我没有意识到你可以在没有循环的情况下这样做
【解决方案2】:

这最初只是一条评论,但事实证明它是您问题的答案。

在这一行:

rot = ((rot & 1 (1 << 31)) >> 31 | (rot << 1);

你有一个额外的1 和一个额外的(,这会阻止它在 gcc 上编译:

main.c: In function ‘hash_function’:
main.c:11:29: error: called object is not a function or function pointer
             rot = ((rot & 1 (1 << 31)) >> 31 | (rot << 1);  
                             ^
main.c:11:58: error: expected ‘)’ before ‘;’ token
             rot = ((rot & 1 (1 << 31)) >> 31 | (rot << 1);  
                                                          ^
main.c:12:9: error: expected ‘;’ before ‘}’ token
         }  
         ^

去掉这两个东西:

rot = (rot & (1 << 31)) >> 31 | (rot << 1);

还有it works

将来,您可能希望找到可以检测此类错误的编译器。我真的很惊讶你的没有。

【讨论】:

  • 这实际上是我所做的复制和粘贴错字,我使用的是检测错误的编译器。但无论如何,非常感谢您的贡献
猜你喜欢
  • 2016-06-23
  • 2018-07-14
  • 2011-10-10
  • 1970-01-01
  • 1970-01-01
  • 2021-12-20
  • 2017-02-04
  • 2012-07-12
  • 2020-09-16
相关资源
最近更新 更多