I've learned that the XOR operator works as OR Exclusive , meaning the end result is only 1 when only one of the operators is equal to 1 .
The truth table illustrates this well:
Myquestionis:howdoestheXORoperatorworkwithnon-1-bitnumbers?
Example:110XOR011
shouldreturnwhichresult?
InJavaScript(oranyotherlanguage)Icanseethattheresultshouldbe101
,buthowdoIgetthisresult?
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);
}