How do I perform a proper unsigned right shift in PHP?

拟墨画扇 提交于 2019-12-23 18:54:38

问题


Is this possible to 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

Is this possible to get the same results?

Closest function to what I want is here:

Unsigned right shift function not working for negative input

Thanks for help.


回答1:


Try this function:

function unsigned_shift_right($value, $steps) {
    if ($steps == 0) {
         return $value;
    }

    return ($value >> $steps) & ~(1 << (8 * PHP_INT_SIZE - 1) >> ($steps - 1));
}

The output, based on your code sample:

1
536870910
16
1073741821
134217727



回答2:


Finally I think I found 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; 
    }


来源:https://stackoverflow.com/questions/25463352/how-do-i-perform-a-proper-unsigned-right-shift-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!