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

后端 未结 8 1429
孤城傲影
孤城傲影 2021-01-13 19:43

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:

         


        
8条回答
  •  南方客
    南方客 (楼主)
    2021-01-13 20:34

    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; 
    }
    

提交回复
热议问题