How can I hash a string to an int using c++?

前端 未结 10 1805
长发绾君心
长发绾君心 2020-12-29 07:27

I have to write my own hash function. If I wanted to just make the simple hash function that maps each letter in the string to a numerical value (i.e. a=1, b=2, c=3, ...), i

10条回答
  •  無奈伤痛
    2020-12-29 08:22

    From personal experience I know that this works and produces good distributions. (Plagiarised from http://www.cse.yorku.ca/~oz/hash.html):

    djb2

    this algorithm (k=33) was first reported by dan 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;
    }
    

提交回复
热议问题