【问题标题】:turning hash key (unsigned long) to int safely将哈希键(无符号长)安全地转换为 int
【发布时间】:2014-05-13 03:40:36
【问题描述】:

我有一个哈希函数:

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

     while (c = *string++)
        {   
           hash = ((hash << 5) + hash) + c;
        }   
     return hash;
  }

我的程序这样称呼它

char testString[] = "Hello World";
unsigned long hashcode = 0;
hashcode = strhash(testString);
int slot = 0;
slot = hashcode%30;

printf("%d\n", slot);

模块是模块我的数组的大小 这是从 unsigned long 安全地转换为 int 吗? 因为它打印出 17 让我觉得它正在工作,但我不确定

【问题讨论】:

  • 为什么不让 slot 也无符号呢?负槽/索引对我来说毫无意义。 (顺便说一句:什么是 tmp ?)

标签: c hash hashcode


【解决方案1】:

注意:我假设您在最后一个语句中的意思是 printf("%d\n", slot);。

通过对 30 进行取模,您实际上将哈希值限制为仅 30 个唯一值(0 到 29)。这大大降低了哈希的有效性,因为许多不同的字符串将映射到相同的哈希值(这 30 个中的一个)。

这个link 为您提供了许多替代哈希函数,包括您问题中djb2 算法的无符号整数版本。请改用其中之一。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-23
    • 2017-01-07
    • 2020-10-31
    • 1970-01-01
    相关资源
    最近更新 更多