I’m currently working with a hash function as such:
unsigned long hashFunc(const char *str, unsigned int tablesize ) // djb2 hash
{
unsigned long hash = 5381;
int c;
while (c = *str++)
hash = ((hash << 5) + hash)+ c; /* hash * 33 + c */
return (hash & tablesize)-1;
}
Apparently, though, the bitwise operator & fails for some long values and returns the max value of long instead. For instance, hashing the word “care” with tablesize of 63 is returning 0xffffffff.
Are bitwise operators not intended to work for unsigned long ints? If so, what other options do I have?
You need to put “-1” within the parenthesis:
This only works if tablesize is known to be a power of two.
If tablesize is not a power of two, then you should use the modulo operator “%”:
(No “-1” is required in this case).