gpt4 book ai didi

php - 从 php 转换为 ruby​​ 时出错

转载 作者:太空宇宙 更新时间:2023-11-03 18:29:21 24 4
gpt4 key购买 nike

您好,我正在尝试用 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;
}

我尝试在 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

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

最佳答案

PHP 不支持任意长度的整数运算,it overflows ,而 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

这给出了 "nzxs"= 2089377688 的正确值

编辑:这篇文章详细解释了PHP中Integer溢出的异常。简而言之,函数的结果取决于您使用的是哪种 PHP 实现。我编辑了该函数以返回该帖子中提到的解决方案的 Ruby 等价物。 Force PHP integer overflow

关于php - 从 php 转换为 ruby​​ 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6465691/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com