views:

411

answers:

2

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

A: 

I studied around the webs and come out with my own zerofill function, base on the explanation given. This method works for my program.

Have a look:

function zeroFill($a,$b) {
    if ($a >= 0) { 
        return bindec(decbin($a>>$b)); //simply right shift for positive number
    }

    $bin = decbin($a>>$b);

    $bin = substr($bin, $b); // zero fill on the left side

    $o = bindec($bin);
    return $o;
}
neobie
A: 

Your function doesn't work because when $b == 0, the expression

$a >> -1

will be evaluated, which returns 0.

Assuming 32-bit machines, you can add a special case:

if ($z & $a) {
  if ($b == 0)
    return $a + 0x100000000;
  else {
    ...
KennyTM