Principle of using an exclusive or exchange data value

Source: Internet
Author: User

We all know that we can use

A ^ = B;
B ^ =;
A ^ = B;

To exchange the values of A and B. Here I will talk about the principle:
^ In C, the bitwise XOR operator is used. If the bitwise XOR operator is used, the result is 0. If it is different, the result is 1. For example, a indicates 5 in decimal format, B Indicates 12 in decimal format, and the result is:

A = 0101 (binary representation of 5)
B = 1100 (binary representation of 12)
----
C = 1001 (result 9)


It can be seen that the Part 1 in C is the part with different bits in binary A and B, and 0 is the same part.

Note the following two principles:
Any binary number with the same 1 variance or will change to another (0 with the same 1 variance or the result is with the same 1 variance or the result is 0)
The binary number of any digit is the same as 0 or both remain unchanged (0 is the same as 0 or 0 is the same as 0, and the result is 1)

Because the Part 1 in C represents the bitwise of A and B, and 0 represents the bitwise of A and B, the result of a's XOR with C is that the bits in a change with B. There are only two States for each binary number, so a is changed to B:
A = 0101
C = 1001.
----
B = 1100


Similarly, the difference or result between B and C becomes:
B = 1100
C = 1001.
----
A = 0101

Principle of using an exclusive or exchange data value

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.