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:
- xorOperation Function: This function performs the XOR operation directly on the binary strings.
- str_pad() Function: Ensures that both binary strings are of equal length by padding them with zeros on the left if necessary.
- For Loop: Iterates over each bit of the binary strings, performing the XOR operation on each pair of corresponding 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