Why are 5381 and 33 so important in the djb2 algorithm?

前端 未结 4 507
南方客
南方客 2020-12-02 05:41

The djb2 algorithm has a hash function for strings.

unsigned long hash = 5381;
int c;

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


        
4条回答
  •  -上瘾入骨i
    2020-12-02 05:59

    On 5381, Dan Bernstein (djb2) says in this article:

    [...] practically any good multiplier works. I think you're worrying about the fact that 31c + d doesn't cover any reasonable range of hash values if c and d are between 0 and 255. That's why, when I discovered the 33 hash function and started using it in my compressors, I started with a hash value of 5381. I think you'll find that this does just as well as a 261 multiplier.

    The whole thread is here if you're interested.

    Ozan Yigit has a page on hash functions which says:

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

提交回复
热议问题