XOR Calculation

Kaycheng
2 min readSep 19, 2021

How to use XOR calculation in Ruby.

What is XOR?

XOR is abbreviation of exclusive OR. It uses on distinguish the value is different or not. And it’s a binary method.

0 ^ 0 = 0
0 ^ 1 = 1
1 ^ 0 = 1
1 ^ 1 = 0

When we do XOR calculation. First step is transform the number to binary. We can use num.to_s(2) to transform the binary to number, then use string.to_i(2) to transform the number to binary. For example:

Question 1: 5 ^ 2 = 7Answer:
5.to_s(2) = "0101"
2.to_s(2) = "0010"
The first row is 0 and 0 => 0 ^ 0 = 0
The second row is 1 and 0 => 1 ^ 0 = 1
The third row is 0 and 1 => 0 ^ 1 = 1
The last row is 1 and 0 => 1 ^ 0 = 1
Then:
"0111".to_i(2) = 7

Question 2: 5 ^ 1 = 4
Answer:
5.to_s(2) = "0101"
1.to_s(2) = "0001"
The first row is 0 ^ 0 = 0
The second row is 1 ^ 0 = 1
The third row is 0 ^ 0 = 0
The last row is 1 ^ 1 = 0
Then:
"0100".to_i(2) = 4

How to calculate?

1. Calculating with self then you will get false.

x ^ x = 0

2. Calculating with 0 then you will get self.

x ^ 0 = x

3. It can change the position randomly.

x ^ y = y ^ x

4. It can combine randomly.

x ^ ( y ^ z ) = ( x ^ y) ^ z

Application

1. Find the single number.

If we have arrays of:

[3, 5, 7, 7, 3] => 5
[1, 2, 2, 4, 1] => 4

How can we find the exclusive number in the array?

We can use XOR method to find the single number:

2. Encrypt the number

For example, when we have four arrays(a1, a2, b1, b2) and we want to use XOR to encrypt them. The array a1 xor a2 to get a1a2, and b1 xor b2 to get b1b2. Then we combine a1a2 and b1b2 to be a hash id.

--

--