Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP equivalent javascript >>> shift right with zero fill bitwise operators?

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

like image 244
neobie Avatar asked Apr 15 '10 00:04

neobie


People also ask

What is the operator for shift right with zero fill?

The unsigned right shift operator ( >>> ) (zero-fill right shift) evaluates the left-hand operand as an unsigned number, and shifts the binary representation of that number by the number of bits, modulo 32, specified by the right-hand operand.

Does PHP have Bitwise Operators?

In PHP, the operators that works at bit level are: & (Bitwise AND) : This is a binary operator i.e. it works on two operand. Bitwise AND operator in PHP takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.

What does >> mean in PHP?

The >> operator is called a binary right shift operator. Shifting bits to the right 4 times is the same as dividing by two, four times in a row. The result, in this case would be 3.125 .

What is >> in bitwise?

>> Indicates the bits are to be shifted to the right. Each operand must have an integral or enumeration type. The compiler performs integral promotions on the operands, and then the right operand is converted to type int .


1 Answers

/**
 * The >>> javascript operator in php x86_64
 * Usage: -1149025787 >>> 0 ---> rrr(-1149025787, 0) === 3145941509
 * @param int $v
 * @param int $n
 * @return int
 */
function rrr($v, $n)
{
    return ($v & 0xFFFFFFFF) >> ($n & 0x1F);
}

/**
 * The >> javascript operator in php x86_64
 * @param int $v
 * @param int $n
 * @return int
 */
function rr($v, $n)
{
    return ($v & 0x80000000 ? $v | 0xFFFFFFFF00000000 : $v & 0xFFFFFFFF) >> ($n & 0x1F);
}


/**
 * The << javascript operator in php x86_64
 * @param int $v
 * @param int $n
 * @return int
 */
function ll($v, $n)
{
    return ($t = ($v & 0xFFFFFFFF) << ($n & 0x1F)) & 0x80000000 ? $t | 0xFFFFFFFF00000000 : $t & 0xFFFFFFFF;
}

Enjoy it.

like image 85
neo.peng Avatar answered Sep 22 '22 10:09

neo.peng