我读以下从Integer Overflow Wiki行:无符号整数溢出不会“环绕”
而无符号整数溢出导致数目减少模 二的幂,即无符号整数“环绕”在 溢出。
我有下面的代码,我试图创建一个哈希函数并得到int溢出情况。我试图通过使用unsigned int
来缓解它,但它不起作用,我能看到负面的价值。
,我知道我能应付其他的方式和它的作品,如在我的代码注释 - Comment 2:
。但它是正确的方式,为什么unsigned int
没有包装和溢出?
int hash(char *word) {
char *temp = word;
unsigned int hash = 0; // Comment 1: I tried to handle int overflow using "unsigned" int.
while (*word != '\0') {
// Comment 2: This works but I do not want to go this way.
//while ((hash * PRIME_MULTIPLIER) < 0) {
// hash = (hash * PRIME_MULTIPLIER) + 2147483647;
//}
hash = hash * PRIME_MULTIPLIER + *word;
word++;
}
printf("Hash for %s is %d\n", temp, hash);
return hash;
}
当你说“没有工作”,你是什么意思? –
请注意,这是素数非常不理想的选择。你基本上正在计算'word [0] - word [1] + word [2] - word [3] ...' –
@ChrisBeck更新。我的意思是我能看到负面的价值。 – hagrawal