开发者

error in conversion from php to ruby

开发者 https://www.devze.com 2023-03-15 07:32 出处:网络
Hi i\'m trying to convert a php function in ruby language. Is there an error because the results are different

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:

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 t开发者_StackOverflow中文版hat i tried to make in ruby is:

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?


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

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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号