Bitwise operators are a category of operators that are used with binary numbers. Each of the operands is converted into a binary number, then manipulated bit by bit. These are mostly useful for manipulating values that have an individual meaning for each bit.
The bitwise operators are for programmers who want to manipulate the bits in various values. Usually we don't use them.
Operator | Name | Description |
---|---|---|
& | And | Returns a one in each bit position for which the corresponding bits of both operands are ones.
e.g. 15 & 9 yields 9 (1111 & 1001 = 1001) |
| | Or | Returns a one in each bit position for which the corresponding bits of either or both operands are ones.
e.g. 15 | 9 yields 15 (1111 | 1001 = 1111) |
^ | Xor | Returns a one in each bit position for which the corresponding bits of either but not both operands are ones.
e.g. 15 ^ 9 yields 6 (1111 ^ 1001 = 0110) |
~ | Not | Inverts the bits of its operand.
e.g. ~ 15 yields 0 (~1111 = 0000) |
<< | Left shift | This operator shifts the first operand the specified number of bits to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right.
e.g. 9<<2 yields 36, because 1001 shifted 2 bits to the left becomes 100100, which is 36. |
>> | Right shift | This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Copies of the leftmost bit are shifted in from the left.
e.g. 9>>2 yields 2, because 1001 shifted 2 bits to the right becomes 10, which is 2. Likewise, -9>>2 yields -3, because the sign is preserved (-9 = 11110111. How do we get -9? We do 2's complement to get the minus sign. First 9 = 00001001. We do 1's complement by inverting bits, i.e. 11110110. Then we add 1 for the 2's complement, i.e. 11110110 + 00000001 = 11110111. When we shift 2 bits (-9>>2), we get 11111101, which is -3. You can verify that it's -3 by doing the 2's complement of 3 with 3 = 0011. Do 1's complement to get 1100. Then add 1 for the 2's complement to get 1101, which is -3). |
<html> <head> <title>PHP</title> <meta Name="Author" Content="Hann So"> </head> <body> <p> <?php echo "15 & 9 yields 9 (1111 & 1001 = 1001) = ", 9&15, "<br />"; echo "15 | 9 yields 15 (1111 | 1001 = 1111) = ", 15|9, "<br />"; echo "15 ^ 9 yields 6 (1111 ^ 1001 = 0110) = ", 15^9, "<br />"; echo "9<<2 yields 36, because 1001 shifted 2 bits to the left becomes 100100, which is 36. = ", 9<<2, "<br />"; echo "9>>2 yields 2, because 1001 shifted 2 bits to the right becomes 10, which is 2 = ", 9>>2, "<br />"; echo "-9>>2 yields -3, because the sign is preserved = ", -9>>2, "<br />"; ?> </p> </body> </html> |