PHP equivalent javascript >>> shift right with zer

2019-02-18 03:08发布

May I know how can I do PHP >>> ? Such operators is not available in PHP, but is available in Javascript.

I just managed to discover a function as follow:

function zeroFill($a, $b) 
{ 
    $z = hexdec(80000000); 
        if ($z & $a) 
        { 
            $a = ($a>>1); 
            $a &= (~$z); 
            $a |= 0x40000000; 
            $a = ($a>>($b-1)); 
        } 
        else 
        { 
            $a = ($a>>$b); 
        } 
        return $a; 
}

but unfortunately, it doesn't work perfectly.

EG: -1149025787 >>> 0 Javascript returns 3145941509 PHP zeroFill() return 0

8条回答
The star\"
2楼-- · 2019-02-18 04:07

For both 32-bit (PHP_INT_SIZE == 4) and 64-bit integers (PHP_INT_SIZE == 8):

function SHR
($x, $c)
{
    $x = intval ($x); // Because 13.5 >> 0 returns 13. We follow.

    $nmaxBits = PHP_INT_SIZE * 8;
    $c %= $nmaxBits;

    if ($c)
        return $x >> $c & ~ (-1 << $nmaxBits - $c);
    else
        return $x;
}
查看更多
等我变得足够好
3楼-- · 2019-02-18 04:11

I've researched a lot on this, collected more than 11 versions from StackOverflow and open-source projects, none of them worked. But finally, I found the solution.

For more details, live demo, tests and examples check my question and answer:
Unsigned Right Shift / Zero-fill Right Shift in PHP (Java/JavaScript equivalent)

function unsignedRightShift($a, $b) {
    if ($b >= 32 || $b < -32) {
        $m = (int)($b/32);
        $b = $b-($m*32);
    }

    if ($b < 0) {
        $b = 32 + $b;
    }

    if ($b == 0) {
        return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1);
    }

    if ($a < 0) 
    { 
        $a = ($a >> 1); 
        $a &= 0x7fffffff; 
        $a |= 0x40000000; 
        $a = ($a >> ($b - 1)); 
    } else { 
        $a = ($a >> $b); 
    }

    return $a; 
}
查看更多
登录 后发表回答