Bitwise Operators
Bitwise operators aren't used very often, and even then only by more advanced PHP programmers. They manipulate the binary digits of numbers, which is more control than many programmers need. The bitwise operators are listed in Table 6-4.
Table 6-4. The bitwise operators
& |
And |
Bits set in |
| |
Or |
Bits set in |
^ |
Xor |
Bits set in |
~ |
Not |
Bits set in |
<< |
Shift left |
Shifts the bits of |
>> |
Shift right |
Shifts the bits of |
To give an example, the number eight is represented in eight-bit binary as 00001000. In a shift left, <<
, all the bits literally get shifted one place to the left, giving 00010000, which is equal to sixteen. Eight shifted left by four gives 10000000, which is equal to 128âthe same number you would have gotten by multiplying eight by two four times in a row.
The &
(bitwise and) operator compares all the bits in operand one against all the bits on operand two, then returns a result with all the joint bits set. Here's an example: given 52 & 28
, we have the eight-bit binary numbers 00110100 (52) and 00011100 (28). PHP creates a result of 00000000, then proceeds to compare each digit in both numbersâwhenever ...
Get PHP in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.