linux golden_ratio_prime 64,_LINUX_HASH_H头文件

#ifndef _LINUX_HASH_H

#define _LINUX_HASH_H

#define BITS_PER_LONG 32

/* Fast hashing routine for a long.

(C) 2002 William Lee Irwin III, IBM */

/*

* Knuth recommends primes in approximately golden ratio to the maximum

* integer representable by a machine word for multiplicative hashing.

* Chuck Lever verified the effectiveness of this technique:

* http://www.citi.umich.edu/techreports/reports/citi-tr-00-1.pdf

*

* These primes are chosen to be bit-sparse, that is operations on

* them can use shifts and additions instead of multiplications for

* machines where multiplications are slow.

*/

#if BITS_PER_LONG == 32

/* 2^31 + 2^29 - 2^25 + 2^22 - 2^19 - 2^16 + 1 */

#define GOLDEN_RATIO_PRIME 0x9e370001UL

#elif BITS_PER_LONG == 64

/* 2^63 + 2^61 - 2^57 + 2^54 - 2^51 - 2^18 + 1 */

#define GOLDEN_RATIO_PRIME 0x9e37fffffffc0001UL

#else

#error Define GOLDEN_RATIO_PRIME for your wordsize.

#endif

static inline unsigned long hash_long(unsigned long val, unsigned int bits)

{

unsigned long hash = val;

#if BITS_PER_LONG == 64

/* Sigh, gcc can't optimise this alone like it does for 32 bits. */

unsigned long n = hash;

n <<= 18;

hash -= n;

n <<= 33;

hash -= n;

n <<= 3;

hash += n;

n <<= 3;

hash -= n;

n <<= 4;

hash += n;

n <<= 2;

hash += n;

#else

/* On some cpus multiply is faster, on others gcc will do shifts */

hash *= GOLDEN_RATIO_PRIME;

#endif

/* High bits are more random, so use them. */

return hash >> (BITS_PER_LONG - bits);

}

static inline unsigned long hash_ptr(void *ptr, unsigned int bits)

{

return hash_long((unsigned long)ptr, bits);

}

#endif /* _LINUX_HASH_H */

int main()

{

long arrary[100000], a = 4;

void *p = (void *)&a;

printf("%d/n", hash_long(100, 4));

//printf("%d/n", hash_ptr(0x12345678, 4);//How to use function hash_ptr

//printf("%d/n", sizeof(&a));

printf("%0x/n", &a);

getchar();

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值