8
I learned that the XOR operator works as OR Exclusive, that is, the end result is only 1 when only one of the operators is equal to 1.
The truth table illustrates this well:
My question is: how the XOR operator works with numbers that are not only 1 bit?
Example: 110 XOR 011
should return what result?
In Javascript (or any other language) I can see that the result should be 101
, but how to get this result?
var a = 6; // 110
var b = 3; // 011
var res = (a ^ b).toString(2);
log('a:', a.toString(2));
log('b:', b.toString(2));
log('res.:', res);
// Apenas pra melhor visualização
function log(label, valor) {
var lb = padLeft(' ', 5, label);
var val = padLeft('0', 3, valor, true);
console.log(lb, val);
}
function padLeft(padChar, padSize, str, left) {
const pad = padChar.repeat(padSize);
if(left)
return (pad + str).slice(-padSize);
else
return (str + pad).substring(0, padSize);
}