<?php
declare(strict_types=1);
function ct_select(
bool $returnLeft,
string $left,
string $right
): string {
$length = mb_strlen($left, '8bit');
if (mb_strlen($right, '8bit') !== $length) {
throw new Exception('ct_select() expects two strings of equal length');
}
// Mask byte
$mask = (-$returnLeft) & 0xff;
// X
$x = (string) ($left ^ $right);
// Output = Right XOR (X AND Mask)
$output = '';
for ($i = 0; $i < $length; $i++) {
$rightCharCode = unpack('C', $right[$i])[1];
$xCharCode = unpack('C', $x[$i])[1];
$output .= pack(
'C',
$rightCharCode ^ ($xCharCode & $mask)
);
}
return $output;
}
var_dump(
ct_select(true, 'apple', 'tiger'),
ct_select(false, 'apple', 'tiger'),
);
preferences:
30.81 ms | 407 KiB | 5 Q