同一个函数在php和javascript上的两个不同输出


Two different outputs from the same function on php and javascript

我有一个函数djb2在php和javascript,php

function hash_djb2($str){
$hash = 5381;
$length = strlen($str);
for($i = 0; $i < $length; $i++) {
    $hash = (($hash << 5) + $hash) + $str[$i];
}
return $hash;
}
javascript

djb2Code = function(str){
var hash = 5381;
for (i = 0; i < str.length; i++) {
    char = str.charCodeAt(i);
    hash = ((hash << 5) + hash) + char; /* hash * 33 + c */
}
return hash;
}

on php I call

hash_djb2("123456789egrdhfdtjdtjdtjrt");

,输出为

-4235984878

在javascript中我调用

djb2Code("123456789egrdhfdtjdtjdtjrt");

,输出为

27338942

这是为什么,我怎么能解决它?

谢谢

它们不是相同的函数。PHP使用$str[$i],这是一个字符。你的JavaScript函数使用char.charCodeAt(i)返回整数

function hash_djb2($str){
    $hash = 5381;
    $length = strlen($str);
    for($i = 0; $i < $length; $i++) {
        $char = ord($str[$i]);                     // this line is added
        $hash = (($hash << 5) + $hash) + $char;    // this line is modified
    }
    return $hash;
}

你必须在PHP代码中使用word

hash = (($hash << 5) + $hash) + ord($str[$i]);