C 中的哈希函数给出一个负数
Hash Function in C giving a negative number
我很好奇问题是我需要不同的哈希函数还是我的代码有问题。我需要散列单词以存储在散列 table 中,一切似乎都适用于该函数但是当我输入很长的单词时,有些单词是 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
函数 returns 和 unsigned long long
,但您将结果存储在 int
.
中
将 key
的类型更改为 unsigned long long
,并使用 %llu
格式说明符打印它。
unsigned long long key = 0;
....
printf("%llu\n", key);
此外,hash
函数中的 hash
变量的类型应为 unsigned long long
,并且应重命名该变量以免与函数名称冲突。
我很好奇问题是我需要不同的哈希函数还是我的代码有问题。我需要散列单词以存储在散列 table 中,一切似乎都适用于该函数但是当我输入很长的单词时,有些单词是 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
函数 returns 和 unsigned long long
,但您将结果存储在 int
.
将 key
的类型更改为 unsigned long long
,并使用 %llu
格式说明符打印它。
unsigned long long key = 0;
....
printf("%llu\n", key);
此外,hash
函数中的 hash
变量的类型应为 unsigned long long
,并且应重命名该变量以免与函数名称冲突。