Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

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))
from operator import xor
c = bytearray(map(xor, a, b))
c = bytes([aa ^ bb for aa, bb in zip(a, b)])
#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++;
}
using System.Linq;
var c = a.Zip(b, (l, r) => (byte)(l ^ r)).ToArray();
use iso_fortran_env, only : int8
integer(kind=int8), dimension(:) :: a, b, c
! Assign values to a and b
c = ieor(a,b)
var c T
for i := range a {
	c[i] = a[i] ^ b[i]
}
c := make([]byte, len(a))
for i := range a {
	c[i] = a[i] ^ b[i]
}
const c = Uint8Array.from(a, (v, i) => v ^ b[i])
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]);
});
(map '(vector (unsigned-byte 8)) #'logxor a b)
local c = {}
for i=1,#a do
	c[i] = string.char(string.byte(a, i) ~ string.byte(b, i))
end
c = table.concat(c)
SetLength(c, Length(a));
for i := Low(a) to High(a) do c[i] := a[i] xor b[i];
use feature 'bitwise';
$c = $a ^. $b;
c = a.zip(b).map{|aa, bb| aa ^ bb}
let c: Vec<_> = a.iter().zip(b).map(|(x, y)| x ^ y).collect();

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