Swap the values of two variables using the XOR operation

1. First of all, it needs to be clear that the XOR operation satisfies the commutative law and the associative law, that is, the following formula

a^b=b^a;
b^a^b=a^b^b;

2, Secondly, the XOR operation also satisfies the following formula

a^a=0;
a^0=a;

3. The code that uses the XOR operation to realize the exchange of variable values ​​between two variables is as follows

a=a^b;
b=a^b;
a=a^b;

4. Analyze the code of the third step as follows

a=a^b;
b=a^b=a^b^b=a^(b^b)=a^0=a;
a=a^b=a^b^a=b^(a^a)=b^0=b;

This achieves the exchange of two variable values ​​using the XOR operation.

5. In the case of daily programming, it is not recommended to use this method. First of all, the speed may not be improved.

6. Another understanding of this method:

1 a^b=diff; // diff is the difference between a and b variables 
2 a^diff=b; // a minus the difference is b 
3 b^diff=a; // b minus the difference for a

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324773385&siteId=291194637