Logo

Programming-Idioms

  • Go
  • C++
  • Fortran

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.

from operator import xor
c = bytes(map(xor, a, b))
from operator import xor
c = bytearray(xor(*x) for x in zip(a, b))
from operator import xor
c = bytes(xor(*x) for x in zip(a, b))

Immutable
from operator import xor
c = bytearray(map(xor, a, b))
c = bytes([aa ^ bb for aa, bb in zip(a, b)])
var c T
for i := range a {
	c[i] = a[i] ^ b[i]
}

T is a fixed-sized array type, e.g. [5]byte.
c := make([]byte, len(a))
for i := range a {
	c[i] = a[i] ^ b[i]
}

Byte slices []byte are more idiomatic than arrays.
#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.
using System.Linq;
var c = a.Zip(b, (l, r) => (byte)(l ^ r)).ToArray();

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