开源软件中 几种经典的Hash算法的实现

本文介绍了哈希算法的基本概念,包括其在数据完整性和快速查找方面的重要作用。文章提供了多个经典软件如PHP、OpenSSL和MySQL中使用的哈希函数实例,并详细解析了它们的设计原理和实现细节。

http://blog.youkuaiyun.com/perfectpdl/article/details/6864351



http://zh.wikipedia.org/wiki/%E5%93%88%E5%B8%8C%E8%A1%A8

http://en.wikipedia.org/wiki/Hash_table

 

 哈希算法将任意长度的二进制值映射为固定长度的较小二进制值,这个小的二进制值称为哈希值。哈希值是一段数据唯一且极其紧凑的数值表示形式。如果散列一段明文而且哪怕只更改该段落的一个字母,随后的哈希都将产生不同的值。要找到散列为同一个值的两个不同的输入,在计算上是不可能的,所以数据的哈希值可以检验数据的完整性。

 

 

链表查找的时间效率为O(N),二分法为log2N,B+ Tree为log2N,但Hash链表查找的时间效率为O(1)。

设计高效算法往往需要使用Hash链表,常数级的查找速度是任何别的算法无法比拟的,Hash链表的构造和冲突的不同实现方法对效率当然有一定的影响,然 而Hash函数是Hash链表最核心的部分,下面是几款经典软件中使用到的字符串Hash函数实现,通过阅读这些代码,我们可以在Hash算法的执行效率、离散性、空间利用率等方面有比较深刻的了解。

下面分别介绍几个经典软件中出现的字符串Hash函数。

●PHP中出现的字符串Hash函数


 
  1. static unsigned long hashpjw(char *arKey, unsigned int nKeyLength)  
  2. {  
  3.       unsigned long h = 0, g;  
  4.        char *arEnd=arKey+nKeyLength;   
  5.   
  6. while (arKey < arEnd) {  
  7. h = (h << 4) + *arKey++;  
  8. if ((g = (h & 0xF0000000))) {  
  9. h = h ^ (g >> 24);  
  10. h = h ^ g;  
  11. }  
  12. }  
  13. return h;  
  14. }  

OpenSSL中出现的字符串Hash函数


 
  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.   
  11. for (i=0; i  
  12. ret^=(s[i]<<(i&0x0f));  
  13. return(ret);  
  14. }   
/* The following hash seems to work very well on normal text strings * no collisions on /usr/dict/words and it distributes on %2^n quite * well, not as good as MD5, but still good. */
  1. unsigned long lh_strhash(const char *c)  
  2. {  
  3. unsigned long ret=0;  
  4. long n;  
  5. unsigned long v;  
  6. int r;   
  7.   
  8. if ((c == NULL) || (*c == '\0'))  
  9. return(ret);  
  10. /* 
  11. unsigned char b[16];  
  12. MD5(c,strlen(c),b);  
  13. return(b[0]|(b[1]<<8)|(b[2]<<16)|(b[3]<<24));  
  14. */   
  15.   
  16. n=0x100;  
  17. while (*c)  
  18. {  
  19. v=n|(*c);  
  20. n+=0x100;  
  21. r= (int)((v>>2)^v)&0x0f;  
  22. ret=(ret(32-r));  
  23. ret&=0xFFFFFFFFL;  
  24. ret^=v*v;  
  25. c++;  
  26. }   
  27.   
  28. return((ret>>16)^ret);  
  29. }  

MySql中出现的字符串Hash函数


 
  1. #ifndef NEW_HASH_FUNCTION   
  2.   
  3. /* Calc hashvalue for a key */  
  4. static uint calc_hashnr(const byte *key,uint length)  
  5. {  
  6. register uint nr=1, nr2=4;   
  7.   
  8. while (length--)  
  9. {  
  10. nr^= (((nr & 63)+nr2)*((uint) (uchar) *key++))+ (nr << 8);  
  11. nr2+=3;  
  12. }   
  13.   
  14. return((uint) nr);  
  15. }   
  16.   
  17. /* Calc hashvalue for a key, case indepenently */  
  18. static uint calc_hashnr_caseup(const byte *key,uint length)  
  19. {  
  20. register uint nr=1, nr2=4;   
  21.   
  22. while (length--)  
  23. {  
  24. nr^= (((nr & 63)+nr2)*((uint) (uchar) toupper(*key++)))+ (nr << 8);  
  25. nr2+=3;  
  26. }   
  27.   
  28. return((uint) nr);  
  29. }  
  30. #else  
  31. /*   
  1. * Fowler/Noll/Vo hash   
  2. *   
  3. * The basis of the hash algorithm was taken from an idea sent by email to the   
  4. * IEEE Posix P1003.2 mailing list from Phong Vo (kpv@research.att.com) and   
  5. * Glenn Fowler (gsf@research.att.com). Landon Curt Noll (chongo@toad.com)   
  6. * later improved on their algorithm.   
  7. *   
  8. * The magic is in the interesting relationship between the special prime   
  9. * 16777619 (2^24 + 403) and 2^32 and 2^8.   
  10. *   
  11. * This hash produces the fewest collisions of any function that we've seen so   
  12. * far, and works well on both numbers and strings.   
  13. */  
  14. uint calc_hashnr(const byte *key, uint len)  
  15. {  
  16. const byte *end=key+len;  
  17. uint hash;   
  18.   
  19. for (hash = 0; key < end; key++)  
  20. {  
  21. hash *= 16777619;  
  22. hash ^= (uint) *(uchar*) key;  
  23. }   
  24.   
  25. return (hash);  
  26. }   
  27.   
  28. uint calc_hashnr_caseup(const byte *key, uint len)  
  29. {  
  30. const byte *end=key+len;  
  31. uint hash;   
  32.   
  33. for (hash = 0; key < end; key++)  
  34. {  
  35. hash *= 16777619;  
  36. hash ^= (uint) (uchar) toupper(*key);  
  37. }   
  38.   
  39. return (hash);  
  40. }  
  41. #endif  
Mysql中对字符串Hash函数还区分了大小写

另一个经典字符串Hash函数


 
  1. unsigned int hash(char *str)  
  2. {  
  3. register unsigned int h;  
  4. register unsigned char *p;   
  5.   
  6. for(h=0, p = (unsigned char *)str; *p ; p++)  
  7. h = 31 * h + *p;   
  8.   
  9. return h;  
  10. }  
 
asterisk 服务器

  1. /*! 
  2.  * \brief Compute a hash value on a case-insensitive string 
  3.  * 
  4.  * Uses the same hash algorithm as ast_str_hash, but converts 
  5.  * all characters to lowercase prior to computing a hash. This 
  6.  * allows for easy case-insensitive lookups in a hash table. 
  7.  */  
  8. static force_inline int attribute_pure ast_str_case_hash(const char *str)  
  9. {  
  10.  int hash = 5381;  
  11.  while (*str) {  
  12.   hash = hash * 33 ^ tolower(*str++);  
  13.  }  
  14.  return abs(hash);  
  15. }  

### C++ 中 `unordered_set` 的哈希函数工作原理 #### 默认哈希函数 在 C++ 标准库中,`unordered_set` 使用标准模板库 (STL) 提供的默认哈希函数来处理内置数据类型。对于常见的内置类型(如 `int`, `float`, `double`, `std::string` 等),C++ STL 已经预定义了相应的哈希函数[^4]。这些默认哈希函数能够满足大多数场景下的需求。 然而,默认哈希函数并不适用于用户自定义的数据类型。在这种情况下,开发者需要显式地为自己的类或结构体定义一个合适的哈希函数。 --- #### 自定义哈希函数的方法 当存储的对象是复杂类型时,可以采用以下两种主要方式来自定义哈希函数: 1. **通过独立的结构体实现** 将哈希逻辑封装在一个单独的结构体内,并将其作为第二个模板参数传入 `unordered_set`。这种方式具有较高的灵活性和可读性。 下面是一个完整的例子,展示如何为 `std::pair<int, int>` 类型创建自定义哈希函数: ```cpp struct MyHash { std::size_t operator()(const std::pair<int, int>& p) const { return std::hash<int>()(p.first) ^ std::hash<int>()(p.second); } }; std::unordered_set<std::pair<int, int>, MyHash> customSet; ``` 2. **重载全局命名空间中的 `std::hash` 特化版本** 另一种方法是对目标类型特化 `std::hash` 模板。这种方法的优点是可以让该类型的实例自动适配所有基于哈希的容器而无需额外指定哈希器。 以下是针对 `Person` 结构体的一个示例: ```cpp struct Person { std::string name_; int age_; bool operator==(const Person& other) const { return name_ == other.name_ && age_ == other.age_; } }; namespace std { template <> struct hash<Person> { size_t operator()(const Person& person) const { size_t res = 17; res = res * 31 + hash<string>()(person.name_); res = res * 31 + hash<int>()(person.age_); return res; } }; } std::unordered_set<Person> peopleSet; ``` --- #### 哈希冲突解决机制 即使有了良好的哈希函数设计,仍然可能遇到不同的键映射到同一个桶的情况,这种现象称为**哈希冲突**。`unordered_set` 内部会利用链表或其他技术管理同一桶内的多个元素,从而保证操作的时间复杂度接近 O(1)。 需要注意的是,为了减少冲突概率并提升性能,建议设计高质量的哈希函数,使得输入分布均匀且不易产生重复值。 --- #### 完整代码示例 下面给出一个综合性的代码片段,演示如何使用自定义哈希函数以及验证其功能: ```cpp #include <iostream> #include <unordered_set> #include <string> // 用户定义的结构体 struct Person { std::string name_; int age_; // 必须定义等于运算符用于比较两个对象是否相等 bool operator==(const Person& other) const { return name_ == other.name_ && age_ == other.age_; } }; // 方法一:通过独立结构体实现哈希函数 struct PersonHasher { size_t operator()(const Person& person) const { size_t res = 17; res = res * 31 + std::hash<std::string>()(person.name_); res = res * 31 + std::hash<int>()(person.age_); return res; } }; int main() { // 创建带有自定义哈希器的 unordered_set std::unordered_set<Person, PersonHasher> people; // 插入一些测试数据 people.insert({"Alice", 30}); people.insert({"Bob", 25}); // 查找某个元素是否存在 if (people.find(Person{"Alice", 30}) != people.end()) { std::cout << "Found Alice!" << std::endl; } else { std::cout << "Not found." << std::endl; } return 0; } ``` --- ### 总结 - 对于简单类型,可以直接依赖 STL 提供的默认哈希函数[^4]。 - 针对复杂的用户自定义类型,则需手动编写适合的哈希算法,推荐的方式包括但不限于定义专用的辅助结构体或者特化 `std::hash` 模板[^2][^3]。 - 设计合理的哈希函数有助于降低碰撞率,进而提高查找效率。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值