PHP Bitwise Operators

In this chapter you will learn:

  1. What are bitwise operators
  2. What are PHP Bitwise Operators
  3. Example - bit calculation

Description

Bitwise operators manipulate the binary digits of numbers.

PHP Bitwise Operators

The bitwise operators are listed in the following table.

Operator Name Description
& And Bits set in $a and $b are set.
| Or Bits set in $a or $b are set.
^ Xor Bits set in $a or $b, but not both, are set.
~ Not Bits set in $a are not set, and vice versa.
<< Shift leftShifts the bits of $a to the left by $b steps.
>> Shift right Shifts the bits of $a to the right by $b steps.

Example

To give an example, the number 8 is represented in eight-bit binary as 00001000. In a shift left, <<, all the bits literally get shifted one place to the left, giving 00010000, which is equal to 16.

The & (bitwise and) operator returns a result with all the joint bits set.

Here's an example: given 52 & 28, we have the eight-bit binary numbers 00110100 (52) and 00011100 (28).

If PHP finds a 1 in both values, it puts a 1 into the result in the same place. Here is how that looks:


00110100 (52) 
00011100 (28)    &
-------------------
00010100 (20) 

Therefore, 52 & 28 gives 20.

Perhaps the most common bitwise operator is |, which compares bits in operand one against those in operand two, and returns a result with all the bits set in either of them. For example:


00110100 (52) 
11010001 (209)    |
------------------
11110101 (245) 

| (bitwise or) operator can combine many options together.

The following code shows how to use bitwise operators.


<?php//from  j a  v  a 2s.c o  m
     $answers = 88;
     $question_four = 8;
   
     $answers = $answers & $question_four;
     print($answers . "<br />");
     $answers = $answers | $question_four;
     print($answers . "<br />");
     $answers = $answers ^ $question_four;
     print($answers . "<br />");
?>

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. What is an execution operator
  2. What is PHP Execution Operator
  3. Example - How to use PHP Execution Operator
Home » PHP Tutorial » PHP Operators
PHP Assignment Operators
PHP Arithmetic Operators
PHP Incrementing and Decrementing Operators
PHP Comparison Operators
PHP Logical Operators
PHP String Operators
PHP Ternary Operator
PHP Bitwise Operators
PHP Execution Operator
PHP Operator Precedence