Open In App

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.

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.

<?php

function xorOperation($bin1, $bin2) {
    $dec1 = bindec($bin1);
    $dec2 = bindec($bin2);
    $xorResult = $dec1 ^ $dec2;
    return decbin($xorResult);
}

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

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

?>

Output
XOR Operation on Binary: 110

Explanation:

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.

<?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++) {
        $result .= (string)((int)$bin1[$i] ^ (int)$bin2[$i]);
    }
    
    return $result;
}

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

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

?>

Output
XOR Operation on Binary: 0110

Explanation:

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

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:

Article Tags :