运算符(Operators)


位运算符(Bitwise Operators)

运算符 符号 使用 例 备注
bitwise AND & $b1 & $b2 bit AND $b1 and $b2
bitwise OR | $b1 | $b2 bit OR $b1 and $b2
complement ~ ~$b1 invert $b1 (0 to 1, 1 to 0)
bitwise XOR ^ $b1 ^ $b2 bit XOR $b1 and $b2
left shift << $b1 << 8 8 digits left shift $b1
right shift >> $b1 >> 8 8 digits right shift $b1
<?php
    $b1 = 0x11;                // 0001 0001
    echo "$b1\r\n";
    $b2 = 0x23;                // 0010 0011
    echo "$b2\r\n";
    $b3 = $b1 & $b2;           // 0000 0001, bit AND
    echo "$b3\r\n";
    $b3 = $b1 | $b2;           // 0011 0011, bit OR
    echo "$b3\r\n";
    $b3 = ~$b1;                // 1110 1110, NOT
    echo "$b3\r\n";
    $b3 = $b1 << 1;            // 0010 0010, left shift 1 digit > double
    echo "$b3\r\n";
    $b3 = $b1 >> 1;            // 0000 1000, right shift 1 digit > half
    echo "$b3\r\n";
?>
[result]  
17
35
1
51
-18
34
8
  • 左移
    依据左移运算符生成的位,其值将一直由零填充。
<?php
    $b1 = 0xFFFFFFFFFFFFFFFF;  // -1
    $b2 = $b1 << 1;            // 0xFFFFFFFFFFFFFFFE (added bit is 0)
    echo "$b2";
?>
[result]  
-2
  • 右移
    依据右移生成的位,将通过同符号位(Sign bit)的值填充。
<?php
    $b1 = 0xFFFFFFFFFFFFFFFF;  // -1
    $b2 = $b1 >> 1;            // 0xFFFFFFFFFFFFFFFF (added bit is 1)
    echo "$b2";
?>
[result]  
-1