Logo

Programming-Idioms

  • Fortran
  • Rust
  • JS
  • Perl
  • C++

Idiom #238 Xor byte arrays

Write in a new byte array c the xor result of byte arrays a and b.

a and b have the same size.

#include <array>
#include <cstddef>
std::array<std::byte, a.size()> c;
for (auto ia = a.begin(), ib = b.begin(); auto & rc : c) {
  rc = *ia++ ^ *ib++;
}

std::byte xor operator requires C++17.
range for init-statement  requires C++20.
use iso_fortran_env, only : int8
integer(kind=int8), dimension(:) :: a, b, c
! Assign values to a and b
c = ieor(a,b)

This uses the int8 constant which is the kind number for a byte.
c is allocated on assignment.
let c: Vec<_> = a.iter().zip(b).map(|(x, y)| x ^ y).collect();
const c = Uint8Array.from(a, (v, i) => v ^ b[i])
use feature 'bitwise';
$c = $a ^. $b;

perl has strings rather than byte arrays, but its built-in xor operator (^) has undefined behaviour when the operands aren't numbers. The 'bitwise' feature enables a operator (^.) that works bitwise on the bytes within strings.
using System.Linq;
var c = a.Zip(b, (l, r) => (byte)(l ^ r)).ToArray();

New implementation...
< >
programming-idioms.org