How to XOR byte arrays in PHP

1 Answer

0 votes
function xorBytes(array $a, array $b): array {
    $result = [];
    for ($i = 0; $i < count($a); $i++) {
        $result[$i] = $a[$i] ^ $b[$i];
    }
    return $result;
}

function printBitsetArray(string $label, array $array): void {
    echo $label . ": ";
    foreach ($array as $byte) {
        echo str_pad(decbin($byte), 8, '0', STR_PAD_LEFT) . " ";
    }
    echo PHP_EOL;
}

// str_split("Albus") = takes the string "Albus" and turns it into an array of characters.
// array_map('ord', ...) = applies the ord() function to each character. 
// ord() gives the ASCII value of a character.
$a = array_map('ord', str_split("Aeryn"));
$b = array_map('ord', str_split("Albus"));
$c = xorBytes($a, $b);

printBitsetArray("a", $a);
printBitsetArray("b", $b);
printBitsetArray("c", $c);

echo "c: ";
foreach ($c as $byte) {
    echo $byte . " ";
}



/*
run:

a: 01000001 01100101 01110010 01111001 01101110 
b: 01000001 01101100 01100010 01110101 01110011 
c: 00000000 00001001 00010000 00001100 00011101 
c: 0 9 16 12 29 

*/

 



answered Jul 12, 2025 by avibootz
edited Jul 12, 2025 by avibootz

Related questions

1 answer 191 views
191 views asked Jul 12, 2025 by avibootz
1 answer 187 views
1 answer 176 views
176 views asked Jul 12, 2025 by avibootz
1 answer 182 views
182 views asked Jul 12, 2025 by avibootz
1 answer 204 views
204 views asked Jul 12, 2025 by avibootz
1 answer 223 views
1 answer 180 views
...