Swap using only two variables using XOR

Different from other languages, the XOR of C language and C++ language does not use xor, but "^", and the typing method is Shift+6. (while "^" in other languages ​​generally means power)
If it is necessary to exchange the values ​​of two variables, in addition to the usual borrowing of intermediate variables for exchange, XOR can also be used to exchange only two variables, such as:
1
2
3
a=a^b;
b=b^a;
a=a^b;
Detailed explanation:
1
2
3
a1=a^b
b=a1^b
a=a1^b=a1^(a1^b)=a1^a1^b=b
gather:
1
a=a^b^(b=a);
This completes the exchange of a and b.
To sum up: the same variable is XORed with another variable and its XOR value is equal to itself.
Use case: It can be used in one or more links of the encryption algorithm to make the algorithm more complex, difficult to be cracked, and more secure.

Guess you like

Origin blog.csdn.net/zp1990412/article/details/39966011