I am using djb2 algorithm to generate a hash key for a string that looks like this
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 each cycle there is a multiplication with two large numbers. After some time, an overflow occurs with the 4th fifth character of the string when 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.
hash string-hashing
Jainish
source share