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。