从php到ruby的转换错误

时间:2022-03-03 21:15:24

Hi i'm trying to convert a php function in ruby language. Is there an error because the results are different The function in php language is:

嗨,我正在尝试转换ruby语言的PHP函数。是否有错误,因为结果不同php语言中的函数是:

function rpHash($value) {
    $hash = 5381;
    $value = strtoupper($value);
    for($i = 0; $i < strlen($value); $i++) {
        $hash = (($hash << 5) + $hash) + ord(substr($value, $i));
    }
    return $hash;
}

The function that i tried to make in ruby is:

我试图在ruby中创建的函数是:

def real_person_hash value
    hash = 5381
    value = value.to_s.upcase
    for i in 0..(value.length - 1)
      hash = ((hash << 5) + hash) + value[i]   
    end
    hash
end

Es.
value = "nzxs"
php function returns:
2089377688
ruby function :
6384344984

I've also noted that the values of the first 3 for cycles are equal. and only in the last cycle the become different Why?

我还注意到前3个循环的值是相等的。只有在最后一个周期变得不同为什么?

1 个解决方案

#1


3  

PHP doesn't support arbitrary length integer arithmetic, it overflows, while Ruby doesn't overflow. You'll need to do something like

PHP不支持任意长度的整数运算,它会溢出,而Ruby不会溢出。你需要做类似的事情

def real_person_hash value
  hash = 5381
  value = value.to_s.upcase
  for i in 0..(value.length - 1)
    hash = ((hash << 5) + hash) + value[i]
  end
  if hash < -2147483648
    -(-(hash) & 0xffffffff)
  elsif hash > 2147483647
    hash & 0xffffffff
  else
    hash
  end
end

This gives the correct value for "nzxs" = 2089377688

这给出了“nzxs”= 2089377688的正确值

Edit: This post explains the abnormality of Integer overflows in PHP in detail. In short, the result of your function depends on which PHP implementation you were using. I've edited the function to return a Ruby equivalent for the solution mentioned in that post. Force PHP integer overflow

编辑:这篇文章详细解释了PHP中Integer溢出的异常。简而言之,函数的结果取决于您使用的PHP实现。我已编辑该函数以返回该帖子中提到的解决方案的Ruby等效项。强制PHP整数溢出

#1


3  

PHP doesn't support arbitrary length integer arithmetic, it overflows, while Ruby doesn't overflow. You'll need to do something like

PHP不支持任意长度的整数运算,它会溢出,而Ruby不会溢出。你需要做类似的事情

def real_person_hash value
  hash = 5381
  value = value.to_s.upcase
  for i in 0..(value.length - 1)
    hash = ((hash << 5) + hash) + value[i]
  end
  if hash < -2147483648
    -(-(hash) & 0xffffffff)
  elsif hash > 2147483647
    hash & 0xffffffff
  else
    hash
  end
end

This gives the correct value for "nzxs" = 2089377688

这给出了“nzxs”= 2089377688的正确值

Edit: This post explains the abnormality of Integer overflows in PHP in detail. In short, the result of your function depends on which PHP implementation you were using. I've edited the function to return a Ruby equivalent for the solution mentioned in that post. Force PHP integer overflow

编辑:这篇文章详细解释了PHP中Integer溢出的异常。简而言之,函数的结果取决于您使用的PHP实现。我已编辑该函数以返回该帖子中提到的解决方案的Ruby等效项。强制PHP整数溢出