Question

I have a hash function:

 unsigned long strhash(char *string)
  {   
     unsigned long hash = 5381;
     int c;

     while (c = *string++)
        {   
           hash = ((hash << 5) + hash) + c;
        }   
     return hash;
  }

and my program calls it like so

char testString[] = "Hello World";
unsigned long hashcode = 0;
hashcode = strhash(testString);
int slot = 0;
slot = hashcode%30;

printf("%d\n", slot);

the module is to module what will be the size of my array is this safely converting from unsigned long to int? because it prints out 17 making me feel like it is working but I am unsure

Was it helpful?

Solution

Note: I assume you meant printf("%d\n", slot); in the last statement.

By doing a modulo with 30, you are effectively restricting the hash value to only 30 unique values (0 to 29). This drastically reduces the effectiveness of the hash, as many different strings will be mapped to the same hash value (one out of those 30).

This link gives you a number of alternative hash functions, including an unsigned int version of the djb2 algorithm in your question. Use one of them instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top