【问题标题】:How to write djb2 hashing function in C?如何用 C 编写 djb2 散列函数?
【发布时间】:2021-02-18 07:12:33
【问题描述】:

我不知道如何在 C 上编写 djb3 散列函数。

我搜索了互联网,但我发现它可能是 C++...

unsigned long hash(unsigned char *str){
        unsigned long hash = 5381;
        int c;

        while (c = *str++)
            hash = ((hash << 5) + hash) + c; /* hash * 33 + c */

        return hash;
    }

如果你能向我解释一下,我将非常感激......

【问题讨论】:

  • 你试过了吗?这对于 C 是有效的(带有警告),但对于 C++ 是无效的,因为缺少返回类型。
  • @MikeCAT 哦,我真的很抱歉我刚刚错过了返回类型。但我刚刚修好了。
  • 你到底需要解释什么?
  • @500-InternalServerError 我只想在我的 c 程序中实现它。所以我需要 C 中的这段代码才能使用它。而且我不知道这段代码在做什么,这些是什么意思... c = *str++ 什么是 hash
  • &lt;&lt; 表示左移(在此上下文中)。 hash &lt;&lt; 5hash * 32 相同,只是效率更高。大多数编译器会自动进行优化,但不一定针对hash * 33,就像这里所要求的那样。

标签: c dictionary hash hashtable


【解决方案1】:

这是djb2 Hashing函数在C编程语言中的代码!

unsigned int hash(const char *word)
{
    unsigned int hash = 5381;
    int c;

    while ((c = *word++))        // *str++ is going to the next address in memory, where the next char in the string is stored
    {
        if (isupper(c))
        {
            c = c + 32;
        }

        hash = ((hash << 5) + hash) + c; // hash * 33 + c   // hash << 5 = hash * 2^5
    }

    return hash % N;
}

感谢@500-InternalServerError 解决了我的疑惑。

【讨论】:

    猜你喜欢
    • 2011-01-15
    • 1970-01-01
    • 2015-05-17
    • 2016-07-21
    • 2011-02-04
    • 1970-01-01
    • 2020-06-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多