C++
unsigned int hash_djb2(char *str, unsigned int str_size)
{
unsigned int hash = 5381;
for(unsigned int c = 0; c < str_size; c++)
hash = ((hash << 5) + hash) + str[c];
return (hash & 0xFFFFFFFF);
}
int main()
{
string term = "one piece";
char* data = const_cast<char*>(term.c_str());
printf("%u", hash_djb2(data, term.size()));//2850035213
}
PHP
<?php
function hash_djb2($str)
{
$hash = 5381;
$length = strlen($str);
for($i = 0; $i < $length; $i++) {
$hash = ( ($hash << 5) + $hash ) + $str[$i];
}
return ($hash & 0xFFFFFFFF);
}
echo hash_djb2("one piece");//-233010523
?>
如何让PHP返回与C++相同的结果?
最佳答案
PHP 中的 str[c]
是问题所在,因为用它加法会尝试解析
作为数字的字符串内容,即。 "123"=>123 和 "O", "n"等简单地变成 0。
使用 ord(str[c])
获取 ASCII 值。
此外,int 转换和更多&0xFFFFFFFF
可能是个好主意,
否则 PHP 可以/将切换为具有更大值的 double。
关于php - hash_djb2 PHP 结果错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24119392/