c - C 中的哈希函数给出负数

标签 c hash hashtable

我很好奇问题是否是我需要不同的哈希函数或者我的代码是否有问题。我需要对单词进行哈希处理以存储在哈希表中,该函数似乎一切正常,但是当我输入很长的单词时,有些单词是 45 个字符,即使我要求返回一个 unsigned long long对我来说,我收到的哈希值是负数。

这是代码,非常感谢您的帮助。

unsigned long long hash(char* str);

int main (void)
{
    int numItems;
    char name[46];
    printf("Please enter how many items will be in your hashtable:");
    scanf("%d", &numItems);

    for (int i = 0; i < numItems; i++)
    {
        int key = 0;
        printf("Please type a name to be entered into the Hashtable:");
        scanf("%s", name);

        //run the word through a hashfunction (simple hashfunction)

       //print the hash number
        key = hash(name);

        printf("%d\n", key);
    }
}
unsigned long long hash(char* str)
    {
        unsigned long hash = 5381;
        int c;
        for (int i = 0; i < strlen(str); ++i) 
            {
                c = (int) str[i];
                hash = ((hash << 5) + hash) + c; 
            }
        return hash;
    }

最佳答案

hash 函数返回一个 unsigned long long,但您将结果存储在 int 中。

key类型更改为unsigned long long,并使用%llu格式说明符打印它。

unsigned long long key = 0;
....
printf("%llu\n", key);

此外,hash 函数内的 hash 变量应具有类型 unsigned long long,并且应重命名该变量,以免与函数名称冲突。

关于c - C 中的哈希函数给出负数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39981175/

相关文章:

c - C 中的简单 Linux Bindshell - 将 Shell 控制返回给客户端

c - "Invalid operands to binary expressions"错误

c++ - 我应该如何在 C++ 中为 unordered_map 定义我自己的哈希函数

php - PHP 与 C 中的箭头运算符

ruby - 将哈希合并到哈希子类 - 确保嵌套哈希具有子类属性

android - Android 的 Facebook 发布 key 哈希不起作用

json - 在 Perl 中,如何打包散列并将其解包回其原始状态?

c - C 的最小哈希函数?

c# - c# 中的文字哈希?

c - 无法将原始套接字绑定(bind)到接口(interface)