The function calculates the hash number, what exactly does it do and why?

I know that this function does something with hash numbers, but did not understand exactly the purpose of this function? why "res * 31 + * key"? why 31?

unsigned int HashAlg(char* key)
{
    unsigned int res = 0;

    while (*key != 0)
    {
        res = res * 31 + *key;
        ++key;
    }

    return res;
}
+5
source share
2 answers

The implementation is a variation of the hash function of the multiplicative string through DJ Bernstein:

unsigned djb_hash ( void *key, int len )
{
  unsigned char *p = key;
  unsigned h = 0;
  int i;

  for ( i = 0; i < len; i++ )
    h = 33 * h + p[i];

  return h;
}

-, , , , "item1", , -, ..; , - , "item1". -, , . Wikipedia.

, 33 31. , -. - - ( , ​​ -). -, , , -. , , ( ) , .. P(Bi = 1) ~= 0.5. , , , , , . -, , - ( PRNG) , " ", .. , ..

+5

"res * 31 + * key"

, , res = res + *key; . , hello, ellh, olleh, loleh .. > 1 .

31?

, 2, . 2 .

0

All Articles