djb2 Hash Function
Posted
by Jainish
on Stack Overflow
See other posts from Stack Overflow
or by Jainish
Published on 2010-04-03T15:32:41Z
Indexed on
2010/04/03
15:43 UTC
Read the original article
Hit count: 626
string-hashing
|hashing
I am using the djb2 algorithm to generate the hash key for a string which is as follows
hash(unsigned char *str)
{
unsigned long hash = 5381;
int c;
while (c = *str++)
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
return hash;
}
Now with every loop there is a multiplication with two big numbers, After some time with the 4th of 5th character of the string there is a overflow as the hash value becomes huge
What is the correct way to refactor so that the hash value does not overflow and the hashing also happens correctly
© Stack Overflow or respective owner