XOR operation derivation, exchange data

WBOY
Release: 2016-08-08 09:20:43
Original
1954 people have browsed it

/*
 * 5 0101
 * 9 1010
 *
 * 5 ^ 5
 * 0101
 * 0101
 * -----
 * 0000
 * 得出第一个规律: 相同的数进行异或, 结果是0
 *
 * 9 ^ 5 ^ 6
 * 1010
 * 0101
 * ----
 * 1111
 *
 * 1111
 * 0110
 * ----
 * 1001
 *
 * 9 ^ 6 ^ 5
 * 1010
 * 0110
 * -----
 * 1100
 *
 * 1100
 * 0101
 * -----
 * 1001
 * 得到第二个规律: 异或的顺序是可以交换的
 *
 * 1001
 * 0000
 * ----
 * 1001
 *
 * 0101
 * 0000
 * ----
 * 0101
 * 得到第三个规律: 任何数和0异或, 结果是本身
 */

//规律1, 相同的数进行异或, 结果是0
//规律2, 异或的顺序可以交换 9 ^ 5 ^ 6 == 9 ^ 6 ^ 5
//规律3, 任何数和0异或, 结果是本身
//推导   a ^ b ^ a = b
//根据2  a ^ b ^ a = a ^ a ^ b
//根据1  a ^ b ^ a = a ^ a ^ b = 0 ^ b
//根据3  a ^ b ^ a = a ^ a ^ b = 0 ^ b = b

echo PHP_EOL;
function swap($a, $b)
{
    $a ^= $b;  //  a = (a ^ b);
    $b ^= $a;  //  b = (a ^ b) ^ b; 结果就是 b = a
    $a ^= $b;  //  a = (a ^ b) ^ (a ^ b ^ b); 两个a合并为0, 两个b合并为0, 最后就剩下b, 结果是 a = b
    echo $a.$b;
}
swap(1, 2);
Copy after login

The above introduces the derivation of XOR operation and exchange of data, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!