Last active
March 22, 2023 02:50
-
-
Save imbyc/0d111076eee5c4752a2dd6036a565a85 to your computer and use it in GitHub Desktop.
[PHP 一致性哈希算法 time33算法]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* time33 函数 | |
* @param string $str | |
* @return 32位正整数 | |
* @author 大神们 | |
*/ | |
function time33($str) | |
{ | |
// hash(i) = hash(i-1) * 33 + str[i] | |
// $hash = 5381; ## 将hash设置为0,竟然比设置为5381分布效果更好!!! | |
$hash = 0; | |
$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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment