hash_djb2 PHP结果错了?

时间:2014-06-09 11:31:09

标签: php c++

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 ++相同的结果?

1 个答案:

答案 0 :(得分:1)

PHP中的str[c]是问题,因为添加它会尝试解析
字符串内容为数字,即。 “123”=&gt; 123和“O”,“n”等变为简单的0 使用ord(str[c])获取ASCII值。

此外,int casts和更多&0xFFFFFFFF可能是一个好主意,
否则PHP可以/将使用更大的值切换为double。