Time33算法

时间:2023-03-09 08:59:52
Time33算法

Time33是字符串哈希函数,现在几乎所有流行的HashMap都采用了DJB Hash Function,俗称“Times33”算法。Times33的算法很简单,就是不断的乘33。

c语言版本

#include "stdio.h"

unsigned int time33(char *);
int main(){
char str[3] = "c语言";
int res; res = time33(str);
printf("%d", res);
} /**
* time33算法
*/
unsigned int time33(char *str){
unsigned int hash = 5381;
while(*str){
hash += (hash << 5 ) + (*str++);
}
return (hash & 0x7FFFFFFF);
}

JAVA版本

public String time33(String skey) {
if (skey == null) return null;
int hash = 5381;
for (int i = 0, len = skey.length(); i < len; ++i) {
int cc = skey.charAt(i);
hash += (hash << 5) + cc;
}
hash &= 0x7fffffff;
return String.valueOf(hash);
}

Javascript版本

//哈希time33算法
function time33(str){
for(var i = 0, len = str.length,hash = 5381; i < len; ++i){
hash += (hash << 5) + str.charAt(i).charCodeAt();
};
return hash & 0x7fffffff;
};

PHP版本

<?php
function myHash($str) {
// hash(i) = hash(i-1) * 33 + str[i]
$hash = 5381;
$s = md5($str); //相比其它版本,进行了md5加密
$seed = 5;
$len = 32;//加密后长度32
for ($i = 0; $i < $len; $i++) {
// (hash << 5) + hash 相当于 hash * 33
//$hash = sprintf("%u", $hash * 33) + ord($s{$i});
//$hash = ($hash * 33 + ord($s{$i})) & 0x7FFFFFFF;
$hash = ($hash << $seed) + $hash + ord($s{$i});
} return $hash & 0x7FFFFFFF;
}

为什么初始值是5381?

5381(001 010 100 000 101),据说hash后的分布更好一些。

Magic Constant 5381:
1. odd number
2. prime number
3. deficient number

参考

CSRF防御 - 为程序员服务 http://ju.outofmemory.cn/entry/75798

PHP: 深入了解一致性哈希 - 陈一回的个人页面 - 开源中国社区

http://my.oschina.net/goal/blog/203593?p=1