How does XOR work for two binaries with more than one digit?

I learned that the XOR operator works as or unique , i.e. the end result is only1 when only one of the operators is equal to 1.

The truth table illustrates this well:

XOR operator truth table, using 1 bit

My question is: how does the XOR operator work with numbers other than just 1 bit?

Example: 110 XOR 011 should return which result?

In JavaScript (or any other language) I can see that the result should be 101, but how to get to 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);
}
Author: LINQ, 2017-05-16

2 answers

The Binary numbering system works no different from the decimal system. Just as the sum or multiplication works the same, so do the logical operators. Therefore the XOR is done bit by bit, as you would add a decimal that is done digit by Digit, with the advantage that it does not have" goes one " in logical operators, nor would it make sense because in this operation the digits have no relation of magnitude, as in arithmetic that a result in one magnitude can affect the result of the other. So:

110  => 1  1  0 (pra visualizar melhor)
011  => 0  1  1
---     -------
101  => 1  0  1

Only the middle one gave 0 because it is not unique. It would have given 0 if it was 0 and 0, as in normal OR.

 11
Author: Maniero, 2017-05-18 11:50:02

The XOR is a mod 2, so if they were:

110
011 

Would be equal:

(1 + 0) mod 2, (1 + 1) mod 2, (1 + 0) mod 2

Assuming , was concatenation, see this in WolfgramAlpha .


When you do this with two letters, for example, literally H and u, for example:

<?php

echo 'H' ^ 'u';
// Resultado: "="

Test this.

Actually this is because its binary values are used, you can also find the table here .

01001000 // str_pad(decbin(unpack('C', 'H')[1]), 8, 0, STR_PAD_LEFT);
01110101 // str_pad(decbin(unpack('C', 'u')[1]), 8, 0, STR_PAD_LEFT);

Applying to same formula above we would have:

00111101

Which has in ASCII (so with in UTF-8) the value of =, remembering that not all ASCII can without"represented" .

So if we did:

echo pack('C', bindec('00111101'));
// Resultado: "="

This is what is done behind the cloths, practically.


I will try to redo this example in Javascript to make it easier to view.

 3
Author: Inkeliz, 2017-05-16 21:57:01