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

8

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:110XOR011shouldreturnwhichresult?

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);
}
    
asked by anonymous 16.05.2017 / 22:46

2 answers

11

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

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 exclusive. You would have given 0 if it were 0 and 0, as in% with normal%.

    
16.05.2017 / 22:50
3

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

110
011 

It would be the same:

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

Assuming that , is concatenation, see this in #

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

<?php

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

Test this.

This is actually because your 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 # would have:

00111101

So if we did:

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

This is what is done behind the scenes, practically.

I'll try to redo this example in Javascript to make it easier to see.

    
16.05.2017 / 23:39