Understanding Bitwise Operators In PHP
Binary math and bitwise operators probably don’t fill you with joy but they are something that need to be understood for certain circumstances or for getting your Zend PHP Certification, so let’s take a look and see if we can uncover the mystery.
What are bits and bytes and binary maths?
In everyday human life we use a base 10 numbering system meaning the number 3429 can be written as so:
3 * 10(3) + 4 * 10(2) + 2 * 10(1) + 9 * 10(0) = 3429
Binary maths however uses the base 2 numbering system which means it has the same concept as base 10 numbering but it only goes in sets of 2, meaning it can only have a value of 0 or 1, lets take a binary number example below:
110101100101 = 1 * 2(11) + 1 * 2(10) + 1 * 2(8) + 1 * 2(6) + 1 * 2(5) + 1 * 2(2) + 1 * 2(0) = 2048 + 1024 + 256 + 64 + 32 + 4 + 1 = 3429
Of course in the examples above all the numbers multiplied by 0 are ignored as multiplying by 0 always equals 0, this means we are left with 6 numbers which when added together gives us the number 3429. So the value 3429 is represented in binary by the value 110101100101.
So what are the bitwise operators and how does this help us?
The operators are as follows: &, |, ^, ~, << and >>
Starting with the & operator, this will return the bits that are set in both variables passed.
Looking below the values 9 and 10 are displayed in decimal as follows:
9 – 00001001
10 – 00001010
This means that the following would return the value 8:
$a = 9;
$b = 10;
echo $a & $b;
But why 8? Lets consider the table below:
As you can see each byte has 8 bits ranging from 1 to 128 and each bit has its own place value, so the reason that the statement above returns the value 8 is because the only place where both numbers have the same bit is in the 8th place value. Easy when you know how!
Using the table above using the | operator would return the value 11 as it asks the question tell me what bits either of you have and add them together.
The ^ operator would return 3 as this asks the question tell me what bits either of you have but don’t let me know about which bits you both have.
The ~ operator would return the number 1 as it is interested in what is set in value $a but not in value $b.
The best case example for using this in normal daily PHP scripts would be to do with user access levels inside a PHP application.
For example you could have super admin set up with the value of 255, admins with 128, editors with 32 etc. right down to the value of 1.
This would mean that anyone with a value of 128 would automatically take on the values of the rest and makes user access a lot more manageable.
If you would like any help with your web development projects then why not get in contact with us here at Network Intellect.