/* * How to use it? Well, string is the null-terminated character string * you need to hash. Buckets is the number of hash buckets you want to * use, which should be a PRIME NUMBER. This helps distribute the hash * values more evenly. Alphabet_size is the length of all the possible * characters that may be in your string. For your basic signed char type, * this would be 127, but you may (as I have) special purpose strings * which use a shorter alphabet. An example of this would be domain names, * which I always force to lower case, and are limited to these * characters: [a-z0-9.-]. The length in that case is 38. Hash_limit is * the maximum number of characters in the string you want to hash. * Generally, this should be 8 or 9. */ unsigned int str_hash(unsigned char *string, unsigned int buckets, unsigned int alphabet_size, unsigned int hash_limit) { int i = 0; unsigned int accum; while ((string[i] != 0) && (i < hash_limit)) i++; if (i < hash_limit) hash_limit = i; accum = (unsigned int) string[hash_limit - 1]; for (i = hash_limit - 2; i >= 0; i--) accum = string[i] + (accum * alphabet_size); return accum % buckets; }