我一直在尝试将char * type c字符串转换为长整数,以便将转换后的数字用作哈希函数的键值。我尝试了atol和strtol函数,每次用不同的字符串调用函数时都返回相同的哈希值。以下是我的哈希函数。
int h_function(char* key,h_table* table){
int i;
char* key_i=key;
char str[14];
char code[4];
char number[11];
long result;
//printf("%c\n",key_i[13]);
//there is a "-" in key[3] so i want to remove that first
for(i=0;i<3;i++){
code[i]=key_i[i];
}
code[3]='\0';
printf("This is the code: %s\n",code);
for(i=0;i<10;i++){
number[i]=key_i[i+4];
}
number[10]='\0';
printf("This is the number: %s\n",number);
strcpy(str,code);
strcat(str,number);
printf("This is the full key number: %s\n",str);
//converting to long int
result=atol(str);
printf("This is the key converted to an integer: %ld\n",result);
int hash_value=(result % table->size);
printf("The hashvalue is: %d\n",hash_value);
return hash_value;
}
这是我得到的输出:
This is the code: 357
This is the number: 5472318696
This is the full key number: 3575472318696
This is the key converted to an integer: 2147483647
The hashvalue is: 22
This is the hashed index: 22
即使完整的键号根据作为参数传递的char *键而改变,转换的整数也与哈希值保持一致。 我希望得到任何帮助......先谢谢。
答案 0 :(得分:1)
那是因为3575472318696不适合int
或long
(我假设你的实现是32位)。
在这种情况下看起来它会返回最大长值,2 ^ 31 - 1 = 2147483647。