Logo

Programming-Idioms

  • Lisp
  • Go
  • JS
  • Python

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 = bytearray(xor(*x) for x in zip(a, b))
c = bytes([aa ^ bb for aa, bb 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))
from operator import xor
c = bytes(map(xor, a, b))
(map '(vector (unsigned-byte 8)) #'logxor a b)

Produces c
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.
const c = Uint8Array.from(a, (v, i) => v ^ b[i])
#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.

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