Times33 DJB Hash 算法

DJB Hash 俗稱 Times33 算法。html

做用:將字符串映射成一個整數算法

用法:顧名思義,每次用HASH 值乘 33,加上字符ASCII值優化

hash(i) = hash(i-1) * 33 + str[i]spa

下面是優化的代碼:.net

unsigned int DJBHash(const char* str, unsigned int length)
{
   unsigned int hash = 5381; //0也沒問題
   unsigned int i    = 0;

   for (i = 0; i < length; ++str, ++i)
   {
      hash = ((hash << 5) + hash) + (*str); //等價hash(i-1) * 33 + str[i]。5(2) = 32(10)
   }

   return hash;
}

/*

Why hash is 5381?

  1. odd numbercode

  2. prime numberhtm

  3. deficient numberblog

  4. 001/010/100/000/101 bci

*/

 

參考文獻:字符串

http://www.partow.net/programming/hashfunctions/#top

http://guyot.blog.163.com/blog/static/120574021201011374439716/

https://stackoverflow.com/questions/10696223/reason-for-5381-number-in-djb-hash-function/13809282

https://stackoverflow.com/questions/1579721/why-are-5381-and-33-so-important-in-the-djb2-algorithm

https://www.cnblogs.com/napoleon_liu/articles/1911571.html

相關文章
相關標籤/搜索