[关闭]
@52fhy 2015-08-23T11:49:24.000000Z 字数 1166 阅读 672

Time33算法

算法


c语言版本

  1. #include "stdio.h"
  2. unsigned int time33(char *);
  3. int main(){
  4. char str[3] = "c语言";
  5. int res;
  6. res = time33(str);
  7. printf("%d", res);
  8. }
  9. /**
  10. * time33算法
  11. */
  12. unsigned int time33(char *str){
  13. unsigned int hash = 5381;
  14. while(*str){
  15. hash += (hash << 5 ) + (*str++);
  16. }
  17. return (hash & 0x7FFFFFFF);
  18. }

JAVA版本

  1. public String time33(String skey) {
  2. if (skey == null) return null;
  3. int hash = 5381;
  4. for (int i = 0, len = skey.length(); i < len; ++i) {
  5. int cc = skey.charAt(i);
  6. hash += (hash << 5) + cc;
  7. }
  8. hash &= 0x7fffffff;
  9. return String.valueOf(hash);
  10. }

Javascript版本

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

PHP版本

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

为什么初始值是5381?
5381(001 010 100 000 101),据说hash后的分布更好一些。

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

参考
CSRF防御 - 为程序员服务 http://ju.outofmemory.cn/entry/75798
PHP: 深入了解一致性哈希 - 陈一回的个人页面 - 开源中国社区
http://my.oschina.net/goal/blog/203593?p=1

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注