A bitwise operation is an operation that works on the individual bits of a number. Yes, that means the binary(base 2) representation of a number. These bitwise operations work by exploiting properties of binary numbers to their advantage. For instance, if the binary representation of a number ends with a 1, it’s odd.
Base 2 Refresher
For those of us who don’t manipulate bits every day (including myself), I thought that a quick refresher on binary representation would be a good idea. First, let’s create a table.
4 | 3 | 2 | 1 | 0 |
0 | 0 | 0 | 0 | 1 |
Each column in the table represents a power of 2. The first column (from the right) represents 20, the second 21, and so on. Notice that I have a 1 in the row below the 0 column. That stands for 20, and 20 is equal to 1. Therefore, the number represented above (00001) is equal to 1. On to the next table.
4 | 3 | 2 | 1 | 0 |
0 | 0 | 1 | 1 | 1 |
4 | 3 | 2 | 1 | 0 |
1 | 1 | 0 | 0 | 1 |
Trick 1 : Odd / Even
One of the most useful bitwise tricks for web developers is for determining if a number is even or odd.
for($i = 0; $i < 10; $i++) { if($i & 1) { echo "This is odd."; } else { echo "This is even."; } } |
Trick 2 : Multiplication and Division
//Example 1 $x = 2; echo $x << 1; //4 echo $x << 2; //8 //Example 2 $x = 16; echo $x >> 1; //8 echo $x >> 2; //4 |
In example 1, we left shift the number 2 one place. By left shifting 1 place, it’s the same as multiplying that number by 2. By left shifting 2 places, it’s the same multiplying the number by 2 twice.
Example 2 is doing bitwise division. Right shifting by 1 place is the same as dividing the number by 2. Right shifting by 2 places, is the same is the same as dividing the number by 2 twice.
Others
There are most definitely a ton of other uses for bitwise operators, however these are the ones I use the most. If you happen to have a favorite, please let everyone know about it in the comments.
For a more in depth introduction to bitwise operations please check out http://en.wikipedia.org/wiki/Bitwise_operation and http://www.litfuel.net/tutorials/bitwise.htm