位操作哈希 rotate_hash

 

#include<stdio.h>
#include<string.h>
#include <stdlib.h>
#include <stdint.h>

uint32_t rotate_hash(char *key, uint32_t len, uint32_t mask)
{
  uint32_t hash, i;
  for (hash=0, i=0; i<len; ++i)
    hash = (hash<<5)^(hash>>27)^key[i];
  return hash = (hash ^ (hash>>10) ^ (hash>>20)) & mask; // replace (hash % prime);
}


int main(int argc, char **argv)
{
    char name[1024];
    int init =0;
    if(argc == 2) {
        init = atoi(argv[1]);
    }
    while(gets(name)>0){
        int len = strlen(name);
        printf("%u\n",rotate_hash(name, len, 0xffffffff));
    }
    return 0;
}


 

测试后,冲突率在1/1000. 比time33差一些。

这个hash,出现在《计算机编程艺术》卷3中。

posted @ 2010-12-25 11:06  napoleon_liu  阅读(391)  评论(0编辑  收藏  举报