How to XOR byte arrays in Node.js

1 Answer

0 votes
function xorBytes(a, b) {
    const result = new Uint8Array(a.length);
     
    for (let i = 0; i < a.length; i++) {
        result[i] = a[i] ^ b[i];
    }
     
    return result;
}
 
function printBitsetArray(label, array) {
    let output = label + ": ";
     
    for (let byte of array) {
        output += byte.toString(2).padStart(8, '0') + " ";
    }
     
    console.log(output);
}
 
// Initialize arrays using ASCII codes
const a = new Uint8Array([..."Aragorn"].map(ch => ch.charCodeAt(0)));
const b = new Uint8Array([..."Boromir"].map(ch => ch.charCodeAt(0)));
 
const c = xorBytes(a, b);
 
printBitsetArray("a", a);
printBitsetArray("b", b);
printBitsetArray("c", c);
 
process.stdout.write("c: ");
for (let byte of c) {
    process.stdout.write(byte + " ");
}
 
 
 
/*
run:
 
a: 01000001 01110010 01100001 01100111 01101111 01110010 01101110 
b: 01000010 01101111 01110010 01101111 01101101 01101001 01110010 
c: 00000011 00011101 00010011 00001000 00000010 00011011 00011100 
c: 3 29 19 8 2 27 28 
 
*/ 

 



answered Jul 12 by avibootz

Related questions

1 answer 27 views
1 answer 38 views
1 answer 30 views
1 answer 30 views
1 answer 31 views
31 views asked Jul 12 by avibootz
1 answer 34 views
...