How does the C language use xor for the exchange of two values

  • 2020-05-30 20:48:08
  • OfStack

C language xor operation

The most commonly used of the family of bitwise operators, an extranodal or operator.

The xor operator refers to the two values that participate in the operation. If the two corresponding bits are the same, the result is 0, otherwise, it is 1. So 0 to the 0 is 0, 1 to the 0 is 1, 0 to the 1 is 1, 1 to the 1 is 0

For example: 10100001 ^ 00010001 = 10110000

0 to the 0=0,0 to the 1=1

1 to the 0=1,1 to the 1=0

Any number or itself is equal to putting itself at 0

1) bitwise hetero or can be used to flip some specific bits, such as the first bit and the second bit of logarithm 10100001, which can be used to perform bitwise hetero or operation between Numbers and 00000110.

10100001 ^ 00000110 = 10100111

In base 106:0xA1 ^ 0x06= 0xA7

(2) through bitwise xor operation, the exchange of two values can be realized without the use of temporary variables. For example, the exchange of two integers a and b values can be achieved through the following statements:

a=10100001, b=00000110

a = a ^ b; / / a = 10100111

b = b ^ a; / / b = 10100001

a = a ^ b; / / a = 00000110

(3) the characteristic of the xor operator is that the number a is the same or the same twice. The number b (a=a^b^b) is still the original value a.

The exchange of two values is carried out using the exclusive or

The xor has two very important properties:

1. A^A = 0;

2. A^0 = A;

Using these two properties, we are able to exchange two values using xor.

The code is as follows:


#include <stdio.h>

int main()
{
 int a = -11;
 int b = -1;
 
 a = a^b;
 b = a^b;
 a = a^b;

 /* Or we could write it for short 
  * 
 a ^= b;
 b ^= a;
 a ^= b
 *
 **/
 printf(" After exchanging a = %d,b = %d\n",a,b);
 return 0;
}

conclusion


Related articles: