You are currently viewing What is Bitwise Operators in PHP | Explained
  • Post category:PHP

What is Bitwise Operators in PHP | Explained

Bitwise Operators in PHP

In this article, we will see about bitwise operators in php.

Bitwise operators

Bitwise operators are used to performing operations on bits. It converts the given decimal number to its binary equivalent number, and then they perform the operation on those bits and return the result in the form of a 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.

Example:

<?php
echo 1 & 1; //1
echo 2 & 5; //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.

Example:

<?php
echo 1 | 1; //1
echo 1 | 0; //1
echo 0 | 1; //1
echo 0 | 0; //0
?>

^ : Bitwise Exclusive OR operator

If both LHS and RHS operands are the same then the result will be 0, otherwise, the result will be 1.

Example:

<?php
echo 1 ^ 1; //0
echo 1 ^ 0; //1
echo 0 ^ 1; //1
echo 0 ^ 0; //0
?>

~ : Bitwise Complement operator

Add 1 to the given number and change the sign.

Example:

<?php
echo ~ 3; // -4
echo ~ (-3); //2
echo ~ 5; // -6
?>

<<: Bitwise Left shift operator

Shifts the bits of the first number to the left by a number of positions indicated by the second number.
firstNumber * pow(2, secondNumber)

Example:

<?php
echo 1<<4; // 16
echo 12<<2; //46
?>

>>: Bitwise Right shift operator

Shifts the bits of the first number to the right by a number of positions indicated by the second number.
firstNumber * pow(2, secondNumber)

Ex:

<?php
echo 16>>4; // 1
echo 48>>2; //12
?>

Leave a Reply