سؤال

What I know for A XOR B operation is that the output is 1 if A != B, and 0 if A == B. However, I have no insight about this operation when A and B are not binary.

For example, if A = 1, B = 3, then A XOR B = 2; also, if A = 2, B = 3, then A XOR B = 1. Is there any pattern to the XOR operation for non-binary values?

I have a good understanding of boolean mathematics, so I already understand how XOR works. What I am asking is that how do you, for example, predict the outcome of A XOR B without going through the manual calculation, if A and B are not binaries? Let's pretend that 2 XOR 3 = 1 is not just a mathematical artifact.

Thanks!

هل كانت مفيدة؟

المحلول

Just look at the binary representations of the numbers, and perform the following rules on each bit:

0 XOR 0 = 0
0 XOR 1 = 1
1 XOR 0 = 1
1 XOR 1 = 0

So, 1 XOR 3 is:

1   =  001
3   =  011
XOR =  010  =  2

To convert a (decimal) number to binary, repeatedly divide by two until you get to 0, and then the remainders in reverse order is the binary number:

To convert it back, repeatedly subtract it by the largest power of two that's no bigger than it until you get to 0, having each position in the binary number corresponding to the powers you subtracted by set to 1 (the left-most position corresponds to the 0-th power):

(Images reference)

نصائح أخرى

xor on integers and other data is simply xor of the individual bits:

A:    0|0|0|1    = 1
B:    0|0|1|1    = 3
      =======
A^B:  0|0|1|0    = 2

          ^-- Each column is a single bit xor         

When you use bit operations on numbers that are more than one bit, it simply performs the operation on each corresponding bit in the inputs, and that becomes the corresponding bit in the output. So:

A = 1 = 00000001
B = 3 = 00000011
        --------
result= 00000010 = 2

A = 2 = 00000010
B = 3 = 00000011
        --------
result= 00000001 = 1

The result has a 0 bit wherever the input bits were the same, a 1 bit wherever they were different.

You use the same method when performing AND and OR on integers.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top