public class XORBytesDemo {
// XOR two byte arrays of the same length
public static byte[] xorBytes(byte[] a, byte[] b) {
byte[] result = new byte[a.length];
for (int i = 0; i < a.length; i++) {
result[i] = (byte)(a[i] ^ b[i]);
}
return result;
}
// Print byte array as 8-bit binary strings
public static void printBitsetArray(String label, byte[] array) {
System.out.print(label + ": ");
for (byte b : array) {
String bits = String.format("%8s", Integer.toBinaryString(b & 0xFF)).replace(' ', '0');
System.out.print(bits + " ");
}
System.out.println();
}
public static void main(String[] args) {
byte[] a = {'A', 'e', 'r', 'y', 'n'};
byte[] b = {'A', 'l', 'b', 'u', 's'};
byte[] c = xorBytes(a, b);
printBitsetArray("a", a);
printBitsetArray("b", b);
printBitsetArray("c", c);
System.out.print("c: ");
for (byte ch : c) {
System.out.print((ch & 0xFF) + " ");
}
}
}
/*
run:
a: 01000001 01100101 01110010 01111001 01101110
b: 01000001 01101100 01100010 01110101 01110011
c: 00000000 00001001 00010000 00001100 00011101
c: 0 9 16 12 29
*/