Time33算法
2015-11-30 16:01
183 查看
Time33是字符串哈希函数,现在几乎所有流行的HashMap都采用了DJB Hash Function,俗称“Times33”算法。Times33的算法很简单,就是不断的乘33。
c语言版本
JAVA版本
Javascript版本
PHP版本
为什么初始值是5381?
5381(001 010 100 000 101),据说hash后的分布更好一些。
参考
CSRF防御 - 为程序员服务 http://ju.outofmemory.cn/entry/75798
PHP: 深入了解一致性哈希 - 陈一回的个人页面 - 开源中国社区
http://my.oschina.net/goal/blog/203593?p=1
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
相关文章推荐
- C++primer plus第六版课后编程练习答案10.5
- Cookie的使用讲解及示例
- 前后台校验示例及讲解
- Hibernate Validation使用示例及讲解
- Jquery Validation实用示例及讲解
- SpringMVC下打包文件的下载
- Chrome下最简分页打印方案
- 基于JDK API实现文件的压缩与解压
- 使用Spring发送基于freemarker模板的邮件
- SpringMVC下Excel文件的上传下载实现
- 地址重写
- Git解惑
- Binder的实现
- 技术经理角色的几点思考
- 深入理解控件(ViewRoot)系统(节选)
- 你真的了解实时计算吗?
- Ajax
- Android 蓝牙BLE (蓝牙成长之路)4
- Web.xml配置详解
- MyBatis与Spring集成