Javascript >>> PHP equivalent shift right with zero padding bitwise operators?

Can I find out how I can do PHP β†’>? Such operators are not available in PHP, but are available in Javascript.

I just managed to find the following function:

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 does not work perfectly.

EG: -1149025787 β†’> 0 Javascript returns 3145941509 PHP zeroFill () returns 0

+4
source share
7 answers

I studied web pages and exited with my own zerofill function, based on the explanation given. This method works for my program.

Take 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;
}
0
source

function zerofill($a,$b) { 
    if($a>=0) return $a>>$b;
    if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1);
    return ((~$a)>>$b)^(0x7fffffff>>($b-1)); 
+2

, , $b == 0,

$a >> -1

0.

32- , :

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

, php, #.

int a, b, result;
//Instead of 
result = a >>> b;
//I do
result = (int)((uint)a >> b);

, , >>>, # , javascript. b = 0 , hex/dec >> >>>, javascript. a , >>> aa unsigned.

, , >>> md5. , .

,

+1

32- (PHP_INT_SIZE == 4) 64- (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;
}
+1

, 11 StackOverflow , . , , .

, :
/- PHP ( Java/JavaScript)

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 &= 2147483647; 
        $a |= 0x40000000; 
        $a = ($a >> ($b - 1)); 
    } else { 
        $a = ($a >> $b); 
    }

    return $a; 
}
+1

function RRR($a, $b){
    return (int)((float)$a/pow(2,(int)$b));
}
0

All Articles