几个常用字符串hash算法的node封装
发布于 9 年前 作者 qingdu 11668 次浏览 最后一次编辑是 3 年前

<p>为下一步开发做的一些技术储备</p> <br/><p>把一些常用的字符串hash算法做了一下封装</p> <br/><p>代码如下</p> <br/> <br/><pre escaped=“true” lang=“javascript” line=“1”> <br/>// hash.js <br/>exports.additive = function (key, prime) { <br/> key = key instanceof Buffer ? key : new Buffer(key); <br/> prime = prime == undefined ? 0xffffffff : prime; <br/> for (var hash = key.length, i = 0; i < key.length; i++) { <br/> hash += key[i]; <br/> } <br/> return (hash % prime); <br/>} <br/> <br/>exports.rotating = function(key) { <br/> key = key instanceof Buffer ? key : new Buffer(key); <br/> for (var hash = key.length, i = 0; i<key.length; ++i) { <br/> hash = (hash << 4) ^ (hash >> 28) ^ key[i]; <br/> } <br/> return hash; <br/>} <br/> <br/>exports.bernstein = function(key, prime) { <br/> key = key instanceof Buffer ? key : new Buffer(key); <br/> prime = prime == undefined ? 0xffffffff : prime; <br/> var hash = 0; <br/> for (i=0; i<key.length; ++i) { <br/> hash = (hash << 5 + hash) + key[i]; <br/> } <br/> return hash; <br/>} <br/> <br/>exports.fnv = function (key){ <br/> key = key instanceof Buffer ? key : new Buffer(key); <br/> var p = 16777619, hash = 0x811C9DC5; <br/> for(var i=0; i< key.length; i++) { <br/> hash = (hash * p) ^ key[i]; <br/> } <br/> hash += hash << 13; <br/> hash ^= hash >> 7; <br/> hash += hash << 3; <br/> hash ^= hash >> 17; <br/> hash += hash << 5; <br/> return hash; <br/>} <br/> <br/>exports.fnv1a = function (key){ <br/> key = key instanceof Buffer ? key : new Buffer(key); <br/> var p = 16777619, hash = 0x811C9DC5; <br/> for(var i=0; i< key.length; i++) { <br/> hash = (hash ^ key[i]) * p; <br/> } <br/> hash += hash << 13; <br/> hash ^= hash >> 7; <br/> hash += hash << 3; <br/> hash ^= hash >> 17; <br/> hash += hash << 5; <br/> return hash; <br/>} <br/></pre>

4 回复

bernstein/time33算法在PHP里有个改进,它把初始的hash值改成了 5381(001 010 100 000 101),据说hash后的分布更好一些.

这个数字还集 素数、奇数和缺数于一身,膜拜!

写这个的时候考虑过几个常用的33常数 <br/>33, 131, 1313, 5381之类的这些, <br/>不过从位运算角度考虑, 还是33合适

乘33没错,var hash = 0; 这个初始值PHP给的是5381

回到顶部