Operator |
Description |
Example |
& |
Bitwise AND |
$m & $n |
| |
Bitwise OR |
$m | &$n |
##^ | Bitwise XOR | $m ^ $n |
~ | Bitwise negation or bitwise inversion | $m ~ $n |
##< ;Shift left |
$m |
| >>
Shift right |
$m >> $n |
|
Let’s use examples to describe the operators in the above table
<?php
$m=1; //1=0 00000001
$n=2; //2=00000010
$mn=$m&$n;
echo $mn."<br/>";
$mn=$m^$n;
echo $mn."<br/>";
$mn=$m|$n;
echo $mn;
?>
Code running results:
Example explanation :
$m&$n : 1 when both are 1, otherwise 0. That is, set the bits in $a and $b that are both 1 to 1, otherwise set to 0.
00000001 ← $m
& 00000010 ← $b
The comparison result is 00000000, so the output is 0
$m^$ n: In the process of bitwise OR, the difference is 1 and the same is 0.
00000001 ← $m
^ 00000010 ← $n
So the result is 00000011, and 3 is output.
$m|$n: In the process of bitwise OR, 1 is 1, all 0 is 0,
00000001 ← $m
| 00000010 ← $n
The result is 00000011, so the output is 3
The above example talks about "bitwise OR", "bitwise OR", "bitwise XOR", let's take a look at the next three examples
Bitwise NOT or bitwise negation example, the code is as follows
<?php
$m = 2;
$m1 = ~$m;
echo $m1;
?>
Running results
At this time our running result is -3, we need to pay attention here.
Note: In computers, negative numbers are expressed in the complement form of their positive values.
1: The 32-bit original code of 2 is 0000 0000 0000 0000 0000 0000 0000 0010
2: The bitwise inversion is 1111 1111 1111 1111 1111 1111 1111 1101
Since the first number is 1 and the sign bit is 1, it is a negative number. Therefore, the complement form of its positive value is expressed as: (the sign bit remains unchanged, bitwise inversion, and 1 is added at the end)
1000 0000 0000 0000 0000 0000 0000 0011
So the output is -3
Left shift right shift code example
<?php
$m = 12; // 12=00001100
$n = 3; // 3=00000011
$mn= $m << $n;
echo $mn ."<br/>";
$mn= $m >> $n;
echo $mn ;
?>
Running results:
Example explanation:
$m: Move the bits in $m to the left $n times (each move means "multiply by 2", that is, "multiply by 2$b").
0000 1100 ← $m
##0110 0000 = 96
$m>>$n: Move the bits in $m to the right $n times (each move means "divide by 2", that is, "multiply by 2 -$b "). 0000 1100 ← $m
0000 0001 = 1
The above content is the detailed content of "bit operators" in PHP operations. If you don't understand anything, you can follow our PHP Chinese website and leave a message above. We will I will give you the answer as soon as possible or search on the PHP Chinese website, you may be able to find what you want. In the next section, we will introduce in detail the logical operators in PHP operations.