Operators
Bitwise Operators
Operator |
Sign |
Syntax |
Additional Information |
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 |
- Example of Bitwise operators
<?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
- Left Shift
Added bits by left shift operation are always 0.
<?php
$b1 = 0xFFFFFFFFFFFFFFFF; // -1
$b2 = $b1 << 1; // 0xFFFFFFFFFFFFFFFE (added bit is 0)
echo "$b2";
?>
[result]
-2
- Right Shift
Added bits by right shift operation are always the same with sign bit.
<?php
$b1 = 0xFFFFFFFFFFFFFFFF; // -1
$b2 = $b1 >> 1; // 0xFFFFFFFFFFFFFFFF (added bit is 1)
echo "$b2";
?>
[result]
-1