How do I perform the correct shift without changes in PHP?
Can I get the same results in PHP and Javascript?
Example:
Javascript
<script>
function urshift(a, b)
{
return a >>> b;
}
document.write(urshift(10,3)+"<br />");
document.write(urshift(-10,3)+"<br />");
document.write(urshift(33, 33)+"<br />");
document.write(urshift(-10, -30)+"<br />");
document.write(urshift(-14, 5)+"<br />");
</script>
output:
1 536870910 16 1073741821 134217727
PHP
function uRShift($a, $b)
{
if ($a < 0)
{
$a = ($a >> 1);
$a &= 2147483647;
$a |= 0x40000000;
$a = ($a >> ($b - 1));
} else {
$a = ($a >> $b);
}
return $a;
}
echo uRShift(10,3)."<br />";
echo uRShift(-10,3)."<br />";
echo uRShift(33,33)."<br />";
echo uRShift(-10,-30)."<br />";
echo uRShift(-14,5)."<br />";
output:
1 536870910 0 0 134217727
Can you get the same results?
The closest function to what I want is here:
Unsigned shift function does not work for negative input
Thanks for the help.
+3
source to share
2 answers
Finally I think I have found a solution, I don't know why, but this code works for me:
function uRShift($a, $b)
{
if ($b > 32 || $b < -32) {
$m = (int)($b/32);
$b = $b-($m*32);
}
if ($b < 0)
$b = 32 + $b;
if ($a < 0)
{
$a = ($a >> 1);
$a &= 2147483647;
$a |= 0x40000000;
$a = ($a >> ($b - 1));
} else {
$a = ($a >> $b);
}
return $a;
}
0
source to share