Bitwise operators – The Journey Part II
If you didn’t see the first part of this post click here and enjoy!
This part covers the three operators that Part I left out. The table is the summary, the sections below walk through each one.
| Operator | Name | Rule | Worked example |
|---|---|---|---|
<< |
Shift left | Multiply the left operand by 2 raised to the shift count |
7 << 9 is 7 * 2^9, which is 3584 |
>> |
Shift right | Divide the left operand by 2 raised to the shift count, integer division |
4 >> 6 is 4 / 2^6, which is 0 |
~ |
Not |
~x is -x - 1
|
~9 is -10
|
The « (Shift left) operator
Do you remember our bitwise table from Part I? We are not going to need it anymore. What we are going to do here is simple math, so let’s start with the left shift operator that uses multiplication (*).
The full definition from php is : “Shift the bits of $a $b steps to the left (each step means “multiply by two”)” The rule is: the left operand multiplied by 2 raised to the shift count.
<?php
echo ( 7 << 9 );
left operand = 7;
shift count = 9;
7 * 2 ^ 9 =? (2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2) 2 ^ 9 = 512 7 * 512 =3584
The » (Shift right) operator
“Shift the bits of $a $b steps to the right (each step means divide by two).” Even easier, isn’t it? Let’s try an example!
<?php
echo ( 4 >> 6 );
Can you guess what will be the output?
Our rule this time is: the left operand divided by 2 raised to the shift count.
left operand = 4;
shift count = 6;
4 / 2 ^ 6 =? (2 * 2 * 2 * 2 * 2 * 2) 2 ^ 6 = 64 4 / 64 = 0
The ~ (Not) operator
Finally, we have the last operator, and of course, the easiest one. To use the NOT operator, we must follow the formula ~x = -x -1. For further information, please click here.
<?php
echo ~9;
What we have to do is simply apply the formula shifting the X by 9.
~x = ~9; -x = -9; -1 = -1;
~9 = -9 -1 = - 10
You also might like
About this post
This post was written entirely by a human, without AI assistance.