PHP basic syntax bit operations
People who have written PHP for several years are curious and say that they have never used bit operators. So, if you feel dizzy looking at binary here, just go to T¥M¥D.
Bitwise operators are basically not used, and we also set this knowledge to the understanding level. You don’t have to learn the knowledge about bitwise operators if you don’t want to. Let’s learn it again when we use bit-bit arithmetic in the future.
Knowledge learning level [understanding level, just have an impression].
Example | Explanation | Detailed explanation |
---|---|---|
$ a & $b | And (bitwise AND) | will set the bits in $a and $b that are both 1 to 1. |
$a | $b | Or (bitwise OR) | will set any bit in $a and $b that is 1 to 1. |
$a ^ $b | Xor (bitwise exclusive OR) | will set one of $a and $b to be 1 and the other to 0 bit is set to 1. |
~ $a | Not (Bitwise Negation) | Set the bits in $a that are 0 to 1, and vice versa. |
$a << $b | Shift left | Move the bit in $a to the left $b times (each move means "multiply by 2"). |
$a >> $b | Shift right | Move the bit in $a to the right $b times (each move means "divide by 2"). |
The symbols above are all binary operations.
You will not encounter binary in most cases. If you encounter it, you will be able to make up the knowledge about binary.
<?php //$x二进制值为: $x = 5; //$y二进制值为: $y = 8; //结果为13 echo $x ^ $y; ?>
Variable | Binary value |
---|---|
$x | 0101 |
$y | 1000 |
XOR result | 1101 |
Explanation of XOR: If the two values of x and y are not the same, the result of XOR is 1. If the two values of x and y are the same, the XOR result is 0.
It can be deduced that 1101 is the result of the XOR of $x and $y. The result of 1101 converted using the binary to decimal tool is 13.
Screenshot of online decimal conversion from secondary system to decimal: