Bitwise operators - The Journey
If you are trying to search for bitwise operators on the web, you will find loads of information. However, when I was learning about bitwise operations, none of those resources could clarify my understanding. Finally, I have found a way that is easier and faster to understand bitwise operations. I hope it will help you as well.
The bitwise table
| 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 |
The table above represents the chain of bits that we have. This table will be our guide through the bitwise world. Before we continue, just have a look at the table and see that if we sum up all the values, we will have 255, which means it is the highest value of a bit.
Nevertheless, to achieve 255, all the bits in the table must be true (1).
| 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 | Result |
| 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 255 |
A few more examples:
| 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 | Result |
| 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 10 |
| 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 5 |
Is it easier with the table? What we did is really simple: we took a random number between 0 and 255 and applied it to the table to see its representation in binary. Now we know that 5 in binary is 101 and 10 is 1010.
The & (AND) operator
Here our table become a amazing tool to use. The operator & by definition says: “Bits that are set in both $a and $b are set.” (source). With that definition what will be the result of the following expression:
<?php
echo (5 & 3);
Let’s start with the table where we now have the bitwise operator on the leftmost and the result on the rightmost.
| Operator | 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 | Result |
| & | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 5 |
| & | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 3 |
Using the operator AND, the result of our operation (5 & 3) is 1.
The | (OR) operator
To use the OR operator we will take the same example we used in the AND operator to understand the difference. By definition we have: “Bits that are set in either $a or $b are set.”
<?php
echo (5 | 3);
Applying the documentation definition to the bitwise table should look something like this:
| Operator | 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 | Result | |
| 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 5 | ||
| 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 3 |
This time, the result is 7.
The ^ (XOR) operator
Finally, we are at the XOR operator. It is close to the OR operator but with a big difference. Let’s see what the definition says: “Bits that are set in $a or $b but not both are set.”
<?php
echo (5 ^ 3);
Can you guess what is the output of the operation (5 ^ 3)?
| Operator | 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 | Result | |
| 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 5 | ||
| 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 3 |
Yes, that is right! It is 6.