Introduction to the use of bitwise xor operators in C++

  • 2020-04-01 23:28:55
  • OfStack

The two values involved 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 is equal to 0,0 to the 1 is equal to 1,0 or anything is equal to anything

1 to the 0 is equal to 1,1 to the 1 is equal to 0,1 or anything minus anything


 

Any number or self = put itself at 0

(1) Bitwise or can be used to flip certain bits, such as the second and third bit flips of logarithm 10100001, to perform bitwise xor operations with 00000110.


10100001^00000110=10100111 // 10100001^ 0x06 = 10100001^ 6

 

(2) By performing bitwise xor operations, you can swap two values without having to use temporary variables. For example, exchange the values of two integers a and b, can be achieved by the following statement:


      A = 00000110 = 10100001, b

      A = a ^ b; / / a = 10100111

      B = b ^; / / b = 10100001

      A = a ^ b; / / a = 00000110

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


Related articles: