Open In App

PHP | Bitwise Operators


The Bitwise operators is used to perform bit-level operations on the operands. The operators are first converted to bit-level and then calculation is performed on the operands. The mathematical operations such as addition , subtraction , multiplication etc. can be performed at bit-level for faster processing. In PHP, the operators that works at bit level are:

Below is the implementation of Bitwise Operators in PHP:




<?php
    // PHP code to demonstrate Bitwise Operator.
          
    // Bitwise AND
    $First = 5;
    $second = 3;
    $answer = $First & $second;
      
    print_r("Bitwise & of 5 and 3 is $answer");
      
    print_r("\n");
      
    // Bitwise OR
    $answer = $First | $second;
    print_r("Bitwise | of 5 and 3 is $answer");
      
    print_r("\n");
      
    // Bitwise XOR
    $answer = $First ^ $second;
    print_r("Bitwise ^ of 5 and 3 is $answer");
      
    print_r("\n");
      
    // Bitwise NOT
    $answer = ~$First;
    print_r("Bitwise ~ of 5 is $answer");
      
    print_r("\n");
      
    // Bitwise Left shift
    $second = 1;
    $answer = $First << $second;
    print_r("5 << 1 will be $answer");
      
    print_r("\n");
      
    // Bitwise Right shift
    $answer = $First >> $second;
    print_r("5 >> 1 will be $answer");
      
    print_r("\n");
?>

Output:

Bitwise & of 5 and 3 is 1
Bitwise | of 5 and 3 is 7
Bitwise ^ of 5 and 3 is 6
Bitwise ~ of 5 is -6
5 << 1 will be 10
5 >> 1 will be 2

Article Tags :