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

Asked

Viewed 772 times

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:

Tabela verdade do operador XOR, usando 1 bit

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);
}

2 answers

11


The binary numbering system works no different than the decimal system. Just as sum or multiplication works equal, so do logical operators. So the XOR is bit by bit, as you would add a decimal that is made digit by digit, with the advantage that there is no "going one" in the logical operators, nor would it make sense because in this operation the digits have no relation of greatness, as in arithmetic that a result in one quantity 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 gave 0 because it is not exclusive. It would have given 0 if it were 0 and 0, as in OR normal.

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 , were 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 the same formula above we would have:

00111101

That has in ASCII (as well as in UTF-8) the value of =, recalling that not all ASCII can without "represented".

So if we did:

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

This is what is done behind the scenes, practically.


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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.