Daily Shaarli

All links of one day in a single page.

November 3, 2020

Hash Functions

djb2

This algorithm (k=33) was first reported by Daniel J. Bernstein many years ago in comp.lang.c

Another version of this algorithm (now favored by Bernstein) uses xor: hash(i) = hash(i - 1) * 33 ^ str[i]

The magic of number 33 (why it works better than many other constants, prime or not) has never been adequately explained.

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

    while (c = *str++)
        hash = ((hash << 5) + hash) + c; /* hash * 33 + c */

    return hash;
}