PHP Bitwise Operators
Description
Bitwise operators manipulate the binary digits of numbers.
PHP Bitwise Operators
The bitwise operators are listed in the following table.
Operator | Name | Description |
---|---|---|
& | And | Bits set in $a and $b are set. |
| | Or | Bits set in $a or $b are set. |
^ | Xor | Bits set in $a or $b, but not both, are set. |
~ | Not | Bits set in $a are not set, and vice versa. |
<< | Shift left | Shifts the bits of $a to the left by $b steps. |
>> | Shift right | Shifts the bits of $a to the right by $b steps. |
Example
To give an example, the number 8 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 16.
The & (bitwise and) operator 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).
If PHP finds a 1 in both values, it puts a 1 into the result in the same place. Here is how that looks:
00110100 (52)
00011100 (28) &
-------------------
00010100 (20)
Therefore, 52 & 28 gives 20.
Perhaps the most common bitwise operator is |
, which compares bits in operand
one against those in operand two, and returns a result with all the bits set in either
of them. For example:
00110100 (52)
11010001 (209) |
------------------
11110101 (245)
|
(bitwise or) operator can combine many options together.
The following code shows how to use bitwise operators.
<?php// www.j a va2 s . c o m
$answers = 88;
$question_four = 8;
$answers = $answers & $question_four;
print($answers . "<br />");
$answers = $answers | $question_four;
print($answers . "<br />");
$answers = $answers ^ $question_four;
print($answers . "<br />");
?>
The code above generates the following result.