How does the xor operator work?

For example, there is a task to find a unique value in an array:

a = [1, 2, 3, 4, 5, 1, 2, 3, 4]

You can do:

a.inject(:^)

The result will be 5. That is, it will compare the result of the previous calculation with the new element - (1^2)^3.

But how it works in this example, I do not understand. Why is it coming back?5? With true/false or 1/0 it is clear, but why (1^2) returns 3, and then (3^3) returns 0.

It would be interesting to know and fundamentally (how to apply XOR) and how it works in my example.

Author: Nakilon, 2018-09-26

1 answers

The xor operation is bitwise, i.e. it processes each bit separately. Write the array in binary form in the column

[1, 2, 3, 4, 5, 1, 2, 3, 4]
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
0 0 1
0 1 0
0 1 1
1 0 0 
-----
5 4 5 
----
1 0 1

And count the units in each column. An even number means that the xor of these bits will give zero in the result bit, and an odd number will give one. As a result, 101b=5

 3
Author: MBo, 2018-09-26 10:25:47