Logo

Programming-Idioms

  • JS
  • Kotlin
  • Rust
  • Java

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.

int i, n = a.length;
byte c[] = new byte[n];
for (i = 0; i < n; ++i)
    c[i] = (byte) (a[i] ^ b[i]);
import static java.util.stream.IntStream.range;
int n = a.length;
byte c[] = new byte[n];
range(0, n).forEach(x -> {
    c[x] = (byte) (a[x] ^ b[x]);
});
const c = Uint8Array.from(a, (v, i) => v ^ b[i])
let c: Vec<_> = a.iter().zip(b).map(|(x, y)| x ^ y).collect();
#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