C # using bitwise XOR for exchange

void swap(ref int x, ref int y)
{       x = x ^ y;   y = y ^ x;   x = x ^ y;  }

im finds out about the beaten XOR. how is this exchange going? it blows into my head. this method should swap the contents of X and Y, but I do not understand ALL what is happening?

+3
source share
7 answers

Caution. This method has a very very unpleasant property. It was used in one of the Underhanded C Contest records. It will work with pleasure ... until someone tries something like exchanging two elements of the array: [i] and [j], without guaranteeing that I! = J.

If both references refer to the same variable, this method nullifies it.

+7

Swap-By-XOR.

, , .

, XOR . , , 1- , , . , .

Swap by XOR - "" . :

void Swap( ref int x, ref int y )
{
  x = x + y; 
  y = x - y;
  x = x - y; 
}

, , . , , ... , Swap( ref x, ref x ) , ( ).

+6

.

x|y -> x = x ^ y x|y -> y = y ^ x x|y -> x = x ^ x x|y
0|0              0|0              0|0              0|0
0|1              1|1              1|0              1|0
1|0              1|0              1|1              0|1
1|1              0|1              0|1              1|1

, . , . .

, , " , ", , .

+5

swap() ( i686 x86_64). , , , - , .

+2

XOR swaping , , , , swap -? .

+1

, XOR:

a | b | a^b
- - - - - -
0 | 0 | 0
1 | 0 | 1
0 | 1 | 1
1 | 1 | 0

, xor 1 true, , 0, . - , (+):

x = x ^ y <=> x = x (+) y;
y = y ^ x <=> y = y (+) x;
x = x ^ y <=> x = x (+) y;

: , 0 x, 1 y 1. x, 1 x, y, 0. .

. , 1 x 0 y ( y). , x , 1, XORing y x : y, 1 x. y :)

: x 1, 1, reset 0 1. ? XOR x y , xor? 1, , , .

, , , / , .

+1

: PYTHON:

m,n=map(int,input().split())
m=m^n
n=m^n
m=m^n
print(m,n)

, .

0

Source: https://habr.com/ru/post/1769415/


All Articles