aurain
技术文摘
posts - 137,  comments - 268,  trackbacks - 0

glib库中的哈希函数和比较函数

       最近在项目中需要用到哈希表,要以ip地址构造哈希函数和比较函数。就去网上找了下相关的资料,看了下glib中哈希表中的实现方式,虽然最终没用这个,但既然找了就顺便记录下来,方便查阅。

哈希表是一种提供key-value访问的数据结构,通过指定的key值可以快速的访问到与它相关联的value值。hash表的一种典型用法就是字典,通过单词的首字母能够快速的找到单词。关于哈希表的详细介绍请查阅数据结构的相关书籍,我这里只介绍glib库中哈希表的哈希函数和比较函数。

主要包括针对int, int64, double, string四种数据类型的处理。详细请看下面的代码。

 

typedef char   gchar;

typedef short  gshort;

typedef long   glong;

typedef int    gint;

typedef gint   gboolean;

 

typedef unsigned char   guchar;

typedef unsigned short  gushort;

typedef unsigned long   gulong;

typedef unsigned int    guint;

 

typedef float   gfloat;

typedef double  gdouble;

/* Define min and max constants for the fixed size numerical types */

#define G_MININT8 ((gint8)  0x80)

#define G_MAXINT8 ((gint8)  0x7f)

#define G_MAXUINT8   ((guint8) 0xff)

 

#define G_MININT16   ((gint16)  0x8000)

#define G_MAXINT16   ((gint16)  0x7fff)

#define G_MAXUINT16  ((guint16) 0xffff)

 

#define G_MININT32   ((gint32)  0x80000000)

#define G_MAXINT32   ((gint32)  0x7fffffff)

#define G_MAXUINT32  ((guint32) 0xffffffff)

 

#define G_MININT64   ((gint64) G_GINT64_CONSTANT(0x8000000000000000))

#define G_MAXINT64   G_GINT64_CONSTANT(0x7fffffffffffffff)

#define G_MAXUINT64  G_GINT64_CONSTANT(0xffffffffffffffffU)

 

typedef void* gpointer;

typedef const void *gconstpointer;

 

gboolean

g_int_equal (gconstpointer v1,

        gconstpointer v2)

{

  return *((const gint*) v1) == *((const gint*) v2);

}

 

guint

g_int_hash (gconstpointer v)

{

  return *(const gint*) v;

}

 

gboolean

g_int64_equal (gconstpointer v1,

               gconstpointer v2)

{

  return *((const gint64*) v1) == *((const gint64*) v2);

}

 

guint

g_int64_hash (gconstpointer v)

{

  return (guint) *(const gint64*) v;

}

 

gboolean

g_double_equal (gconstpointer v1,

                gconstpointer v2)

{

  return *((const gdouble*) v1) == *((const gdouble*) v2);

}

 

guint

g_double_hash (gconstpointer v)

{

  return (guint) *(const gdouble*) v;

}

 

gboolean

g_str_equal (gconstpointer v1,

        gconstpointer v2)

{

  const gchar *string1 = v1;

  const gchar *string2 = v2;

 

  return strcmp (string1, string2) == 0;

}

 

guint

g_str_hash (gconstpointer v)

{

  /* 31 bit hash function */

  const signed char *p = v;

  guint32 h = *p;

 

  if (h)

    for (p += 1; *p != '\0'; p++)

      h = (h << 5) - h + *p;

 

  return h;

}

 

posted on 2010-07-06 17:43 阅读(3733) 评论(1)  编辑 收藏 引用 所属分类: c/c++基础知识

FeedBack:
# re: glib库中的哈希函数和比较函数
2010-07-06 22:39 | 飞鸽传书
这么好的东西,现在估计很少人用了,以前开发飞鸽传书(FreeEIM)项目的时候,有考虑过使用GLIB,后来实在是能力有限,未用上。我强烈支持有能力者用这个东西。  回复  更多评论
  

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理



<2008年11月>
2627282930311
2345678
9101112131415
16171819202122
23242526272829
30123456

常用链接

留言簿(17)

随笔分类(138)

随笔档案(137)

网络开发

最新随笔

搜索

  •  

积分与排名

  • 积分 - 488853
  • 排名 - 36

最新随笔

最新评论

阅读排行榜

评论排行榜