1

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 that 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?

Luca Romagnoli
  • 12,145
  • 30
  • 95
  • 157

1 Answers1

3

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

Community
  • 1
  • 1
Dogbert
  • 212,659
  • 41
  • 396
  • 397