·  PHP – Syntax – Operators – Bitwise

 

- Info:

  - Bitwise operators combine bits within one or two integers.

  - This tutorial is based on http://hr.php.net/manual/en/language.operators.bitwise.php.

 

    

Type

Name

Description

 

$a &  $b

AND

Set bits that are set in both $a and $b

 

$a |  $b

OR

Set bits that are set in either $a or $b.

 

$a ^  $b

XOR

Set bits that are different in $a and $b.

 

   ~  $b

NOT

Invert bits

 

$a << $b

Shift left

Shift the bits of $a by $b steps to the left (each step means "multiply by two")

 

$a >> $b

Shift right

Shift the bits of $a by $b steps to the right (each step means "divide by two")

 

- Aditional Info:

  - Right shift >>n is Arithemtic Shift equivalent of dividing by 2n which preserves operand sign.

  - AND, OR, XOR and NOT do not change the value of operands.

 

- Example:

  - Create PHP Console Application Test.php.

 

    Test.php

    <?php

 

      #Test variables.-------------------------------------------------------------------

      $left       = 27;               #11011

      $right      = 18;               #10010

     

      #Bitwise operators.----------------------------------------------------------------

      $and        =  $left & $right;  #10010.    1 if both   bits are 1.

      $or         =  $left | $right;  #11011.    1 if either bit  is  1.

      $xor        =  $left ^ $right;  #01001.    1 if        bits are different.

      $invert     = ~$left;           #11111111111111111111111111100100.  Invert bits.

      $shiftLeft  =  $left << 3;      #11011000. Shift bits to left  by 3 positions. Fill with 0.

      $shiftRight =  $left >> 2;      #110.      Shift bits to right by 2 positions. Fill with sign bit.

 

      #Display results.------------------------------------------------------------------

      print(base_convert($and,10,2));

 

    ?>