Hash 函數大全

轉自 http://blog.csdn.net/free2o/article/details/2199753  點擊打開鏈接


 看到了幾個Hash 函數的計算方法,因此想把所見到的所有Hash code 的計算方法的算法羅列出來。會陸續追加看到的Hash 的算法。 

第一種:  這是MySql 中計算Hash Code 的一個代碼

  1. inline Uint32 Hash( const char* str ){  
  2.   Uint32 h = 0;  
  3.   Uint32 len = strlen(str);  
  4.   while(len >= 4){  
  5.     h = (h << 5) + h + str[0];  
  6.     h = (h << 5) + h + str[1];  
  7.     h = (h << 5) + h + str[2];  
  8.     h = (h << 5) + h + str[3];  
  9.     len -= 4;  
  10.     str += 4;  
  11.   }  
  12.     
  13.   switch(len){  
  14.   case 3:  
  15.     h = (h << 5) + h + *str++;  
  16.   case 2:  
  17.     h = (h << 5) + h + *str++;  
  18.   case 1:  
  19.     h = (h << 5) + h + *str++;  
  20.   }  
  21.   return h + h;  
  22. }  

 

 第二種:這是linux 中計算path hash code 的算法

  1. unsigned long hash (const char * str)  
  2. {  
  3.       unsigned long hs = 0 ;  
  4.       while(*str) {hs = (hs + (* str << 4) + ( * str ++ >> 4))  * 11 ;}  
  5.       return hs;  
  6. }  

第三種:這是Java String 類計算Hash code 的算法
  1. int   hash(const char * str,int len)  
  2. {  
  3.        int h = 0 ,i ;  
  4.        for(i = 0 ; i < len ; i ++) ...{  
  5.              h = h * 31 + str[i];  
  6.        }  
  7. }  

第四種:OpenSSL 項目中lhash.c 文件提供兩種HashCode 的計算方法
  1. unsigned long lh_strhash(char *str)  
  2. {  
  3.      int i,l;  
  4.     unsigned long ret=0;  
  5.     unsigned short *s;  
  6.   
  7.     if (str == NULL) return(0);  
  8.     l=(strlen(str)+1)/2;  
  9.     s=(unsigned short *)str;  
  10.     for (i=0; i<l; i++)  
  11.       ret^=(s[i]<<(i&0x0f));  
  12.      return(ret);  
  13. }  

第五種:OpenSSL 項目中lhash.c 文件提供的第兒種HashCode 的計算方法
  1. /* The following hash seems to work very well on normal text strings 
  2.  * no collisions on /usr/dict/words and it distributes on %2^n quite 
  3.  * well, not as good as MD5, but still good. 
  4.  */  
  5. unsigned long lh_strhash(const char *c)  
  6.     {  
  7.     unsigned long ret=0;  
  8.     long n;  
  9.     unsigned long v;  
  10.     int r;  
  11.   
  12.     if ((c == NULL) || (*c == '/0'))  
  13.            return(ret);  
  14. /* 
  15. unsigned char b[16]; 
  16. MD5(c,strlen(c),b); 
  17. return(b[0]|(b[1]<<8)|(b[2]<<16)|(b[3]<<24)); 
  18. */  
  19.   
  20. n=0x100;  
  21. while (*c)  
  22. {  
  23. v=n|(*c);  
  24. n+=0x100;  
  25. r= (int)((v>>2)^v)&0x0f;  
  26. ret=(ret<<r)|(ret>>(32-r));  
  27. ret&=0xFFFFFFFFL;  
  28. ret^=v*v;  
  29. c++;  
  30. }  
  31. return((ret>>16)^ret);  
  32. }  

第六種:ELF hash 採用的是  DJB (Daniel J Bernstein) hash
  1. uint32_t dl_new_hash (const char *s)  
  2. {  
  3.         uint32_t h = 5381;  
  4.   
  5.         for (unsigned char c = *s; c != '\0'; c = *++s)  
  6.                 h = h * 33 + c;  
  7.         //h = ((h << 5) + h) + c  
  8.         return h;  
  9. }  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章