Bitwise operators - The Journey
If you are trying to search about bitwise operators on web you will find loads of information, although, when I was learning about bitwise none of those in the web could clarify my mind. But finally I have got a way to me is easier and faster to understant bitwise , I hope it will help you either.
The bitwise table
The table above represents the chain of bit that we have. This table will be our guide through the bitwise word, before we continue just have look at the table and see 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 on the table must be true ( 1 )
A few more examples
is it easier with the table ? What we did is really simple we caught a random number between 0 and 255 and applied to the table to see its representation in binary. Now we know 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:
Let's start with the table where now we have on the leftmost the bitwise operator and in the rightmost the result.
Using the operador AND the result of our operation (5 & 3) results in 1
The | (OR) operator
To use the OR operator we will take the same example we used in the AND operator to understand the diference. By definition we have : "Bits that are set in either $a or $b are set."
This time the result is 7
The ^ (XOR) operator
Finally we are in the XOR operator. It is close of OR operator but with a big difference, let's see what the definition say : "Bits that are set in $a or $b but not both are set. "
Can you guess what is the output of the operation (5 ^ 3) ? Yes, that is right ! It is 6.