XOR of Two Binary Strings using Bitwise Operators on Characters

We can also perform the XOR operation on each character of the binary strings individually.

PHP
<?php

function xorOperation($bin1, $bin2) {
    $result = '';
    $length = max(strlen($bin1), strlen($bin2));
    $bin1 = str_pad($bin1, $length, '0', STR_PAD_LEFT);
    $bin2 = str_pad($bin2, $length, '0', STR_PAD_LEFT);

    for ($i = 0; $i < $length; $i++) {
        $bit1 = (int)$bin1[$i];
        $bit2 = (int)$bin2[$i];
        $xorBit = $bit1 ^ $bit2;
        $result .= (string)$xorBit;
    }
    
    return $result;
}

// Driver code
$bin1 = "1101";
$bin2 = "1011";

echo "XOR Operation on Binary: " 
    . xorOperation($bin1, $bin2);

?>

Output
XOR Operation on Binary: 0110

Explanation:

  • xorOperation Function: This function performs the XOR operation on each character of the binary strings.
  • $bit1 and $bit2: Variables that store the individual bits from the binary strings.
  • $xorBit: Stores the result of the XOR operation on the individual bits.


PHP Program for XOR of Two Binary Strings

Given two binary strings, the task is to calculate the XOR of two binary strings in PHP. The XOR operation is a bitwise operation used in computer science and digital electronics. It takes two binary strings as input and produces a binary string as output, where each bit in the output is the result of the XOR operation on the corresponding bits in the input strings.

Table of Content

  • Using Built-in Functions
  • Bitwise XOR on Strings
  • Using Bitwise Operators on Characters

Similar Reads

XOR of Two Binary Strings using Built-in Functions

PHP provides built-in functions like bindec() and decbin() to convert between binary and decimal representations, which can be used to perform the XOR operation....

XOR of Two Binary Strings using Bitwise XOR on Strings

Alternatively, we can perform the XOR operation directly on the binary strings without converting them to decimal....

XOR of Two Binary Strings using Bitwise Operators on Characters

We can also perform the XOR operation on each character of the binary strings individually....