php - hash_djb2 PHP 结果错误?

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

最佳答案

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/

相关文章:

php - 将 mcrypt_generic 转换为 openssl_crypt

php - JavaScript 验证数据库

javascript - 通过ajax将图片文件等多种数据post到php

c++ - 在 O(nlogn) 中查找数组中的所有差异,其中 n 是元素的最大范围

c++ - 编译器选项选择性应用

php - .htaccess:在特定情况下拒绝直接访问文件

php - 从多个表中收集信息并根据不同表中的数据显示的单个查询

c++ - 从恶魔创建一个 fork 进程

c++ - 如何修复 '==' 操作数中比较的建议括号

c++ - DeleteIPAddress 函数有效,但会触发断开连接