If I XOR 2 numbers, do I only get identical results if the numbers are the same?

StackOverflow https://stackoverflow.com/questions/2481587

  •  21-09-2019
  •  | 
  •  

문제

For example, suppose I have x XOR y = y XOR x = z. Is it possible to have something like a XOR b = z?

도움이 되었습니까?

해결책

Yes.

z = y because x ^ y ^ x = y

So it is entirely possible for a combination a ^ b = y = z.

In fact, for every a there exists a b such that a ^ b = z. To calculate that, b = z ^ a.

Be aware that XOR is commutative: this means that x ^ y = y ^ x.

다른 팁

Short answer: Yes

Long answer: XOR is a binary operation, it works on the individual bits and it's commutative.

It has the truth table:

A B  Q
0 0  0
0 1  1
1 0  1
1 1  0

As the number is made up of these bits then the result will be the same as long as for each bit position the two bits have the same result. For example take the 2 eight bit numbers 113 and 42

113 = 01110001
42  = 00101010
XOR = 01011011 = 91

but if I swap the fourth bit from the left I get

97  = 01100001
58  = 00111010
XOR = 01011011 = 91

So yes again...

Yes. As a degenerate proof, XORing a number with itself always results in 0.

XOR, will return true if both parameters are different, assuming that the parameters are Boolean values anyway. This is different from or, which will return true if either parameter is true, and NOR, which will return true only if both of them are false.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top