看了一下GLIB中的GHashTable的源碼,比較有用的字符串哈希函數如下:
/**
* Author:puresky
* Date: 2010/12/21
* Purpose: str_hash
*/
#include <stdio.h>
#include <stdlib.h>//GLIB中的字符串哈希函數[g_str_hash]
unsigned int str_hash(const char *str)
{
const signed char *p = (const signed char*)str;
unsigned int h = *p;
if(h)
{
for(p += 1; *p != '\0'; ++p)
h = (h << 5) - h + *p;
}
return h;
}int main(int argc, char** argv)
{
const char* str = "abc123456abcdefghijklmnopqrstuvwxyz";
const char* p = str;
while(*p != '\0')
{
printf("%s:%un", p, str_hash(p));
p++;
}
system("pause");
return 0;
}
運行結果如下: