Bitwise Operators in PHP
Notes:
PHP Bitwise Operators
Bitwise Operators: are used to perform operations on bits.
Bitwise operators convert the given decimal number(s) to their binary equivalent number, and then they perform the operation on those bits and return the result in the form of decimal
&: Bitwise And operator:
If both LHS and RHS operands are 1 then the result will be 1, in all other cases result will be 0
|: Bitwise Or operator:
If both LHS and RHS operands are 0 then the result will be 0, in all other cases result will be 1
^: Bitwise Exclusive Or operator:
If both LHS and RHS operands are same bits then the result will be 0, otherwise the result will be 1
~: Bitwise complement operator:
Add 1 to the given number and change the sign
<<: Bitwise Left Shift operator:
Shifts the bits of first number to the left by number of positions indicated by second number
firstNumber * pow(2,secondNumber)
>>: Bitwise Right Shift operator:
Shifts the bits of first number to the right by number of positions indicates by second number
firstNumber / pow(2,secondNumber)
Example Code:
echo 1 & 1,"<br/>"; //1
echo 2 & 5,"<br/>"; // 0
echo "<br/>";
echo 1 | 1,"<br/>"; //1
echo 2 | 5,"<br/>"; // 7
echo "<br/>";
echo 1 ^ 1,"<br/>"; //0
echo 2 ^ 5,"<br/>"; // 7
echo "<br/>";
echo ~3,"<br/>"; //-4
echo ~(-3),"<br/>"; //2
echo "<br/>";
echo 1<<4,"<br/>"; // 16
echo 12<<2,"<br/>"; // 48
echo "<br/>";
echo 16>>4,"<br/>"; // 1
echo 48>>2,"<br/>"; // 12
Interview Questions:
1. PHP stands for ______________
a. Hypertext Preprocessor
b. Preprocessor Hypertext
c. Personal Home Processor
d. Personal Hypertext processor
Ans: a