Reputation: 3365
I'm trying to server-side validate a hash generated on the client side.
My client-side js code looks like this:
_hash: function(value) {
var hash = 5381;
for (var i = 0; i < value.length; i++) {
hash = ((hash << 5) + hash) + value.charCodeAt(i);
}
return hash;
}
and my server-side php code like this:
$hash = 5381;
$value = strtoupper($input);
for($i = 0; $i < strlen($value); $i++) {
$hash = (($hash << 5) + $hash) + ord(substr($value, $i));
}
When applied to the string "FMQXXU", you should get -1329107890 on either side.
Both scripts work perfectly on my local environment, but when i move to test on a different machine, only the js code works. The php code returns 6952222944334.
The local php is version 5.3.8, the test php is version 5.3.3.
Why do I get different results?
Upvotes: 2
Views: 100
Reputation: 145
You can use this function to convert 64 bits to 32 bits :
function to_32bits($val) {
$sign = 1 << 31;
return $val & ($sign) ? -(~($val & 0x7fffffff) + 1 + ($sign)) : $val & 0xffffffff;
}
Example :
$a = -1329107890;
$b = 6952222944334;
function to_32bits($val) {
$sign = 1 << 31;
return $val & $sign ? -(~($val & 0x7fffffff) + 1 + $sign) : $val & 0xffffffff;
}
echo $a . ' ' . to_32bits($b);
Will output : -1329107890 -1329107890
I'm not sure if there is a better way to do the conversion.
Upvotes: 1