JS到PHP的错误

问题描述:

I have some JS code which I want to convert to PHP code. I changed all the things that I know should, but it doesn't give the same result.

The PHP code I created from the JS code:

<?php
function hashCode($str){
    $hash = 0;

    if (strlen($str) == 0) return $hash;

    for ($i = 0; $i < strlen($str); $i++) {
          $char = $str[$i];
          $hash = (($hash<<5) - $hash) + $char;
          $hash = $hash & $hash;
    }
    return $hash;
}
?>

When entering a string it returns 0 and that is not because of the if function.
Original code:

hashCode = function(str){
    var hash = 0;
    if (str.length == 0) return hash;
    for (i = 0; i < str.length; i++) {
        char = str.charCodeAt(i);
        hash = ((hash<<5)-hash)+char;
        hash = hash & hash; // Convert to 32bit integer
    }
    return hash;
}

Can someone please help me?

Arend-Jan

我有一些JS代码,我想将其转换为PHP代码。 我改变了所有我应该知道的东西,但它没有给出相同的结果。 p>

PHP代码 strong>我是用JS代码创建的: p>

 &lt;?php 
function hashCode($ str){
 $ hash = 0; 
 
 if if(strlen($ str)== 0)return $ hash;  
 
 for($ i = 0; $ i&lt; strlen($ str); $ i ++){
 $ char = $ str [$ i]; 
 $ hash =(($ hash&lt;&lt; 5  ) -  $ hash)+ $ char; 
 $ hash = $ hash&amp;  $ hash; 
} 
返回$ hash; 
} 
?&gt; 
  code>  pre> 
 
 

输入字符串时 it返回0,那不是因为 if函数。
原始代码: strong> p>

  hashCode = function(str){
 var hash = 0; 
  if(str.length == 0)返回散列; 
 for(i = 0; i&lt; str.length; i ++){
 char = str.charCodeAt(i); 
 hash =((hash&lt;&lt;  ; 5)-hash)+ char; 
 hash = hash&amp; 散列;  //转换为32位整数
} 
返回哈希; 
} 
  code>  pre> 
 
 

有人可以帮助我吗? p>

Arend-Jan p> div>

This is because, in the javascript, the char is the code of the caracter (charCodeAt). So this will do the same. Use ord($char)

function hashCode($str) {
    $hash = 0;
    if (strlen($str) == 0) {
        return $hash;
    }
    for ($i = 0; $i < strlen($str); $i++) {
        $char = $str[$i];
        $hash = (($hash << 5) - $hash) + ord($char);
        $hash = $hash & $hash;
    }
    return $hash;
}

If string is ABCD, the output will be this, in both case:

65
2081
64578
2001986
2001986