djb2 Hash Function
- by Jainish
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