c# using bitwise XOR for swapping

前端 未结 7 1525
借酒劲吻你
借酒劲吻你 2020-12-18 12:40
void swap(ref int x, ref int y)
{       x = x ^ y;   y = y ^ x;   x = x ^ y;  }

im learning about bitwise XOR. how is this swapping occurring? it\'

7条回答
  •  死守一世寂寞
    2020-12-18 13:22

    Wikipedia has an excellent explanation of the Swap-By-XOR algorithm.

    The formal proof that this algorithm works is a bit involved, and requires the use of the mathematical properties of binary numbers.

    But in simplified form, we can consider each bit of the binary value separate, since the XOR operation acts on each independently. As such, it's sufficient to show that this works with 1-bit values, since by induction we can demonstrate it works for any length binary value. It's quite simple to build an appropriate truth table for these operations, so I leave that out.

    Swap by XOR is not the only "creative" swapping algorithm possible. A similar result can be achieved by using arithmetic operations:

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

    From a practical perspective, this is a technique that should be avoided in most cases. As you yourself recognize, the logic of this method is not immediately obvious and it can lead to maintainability and extensibility problems ... not the least of which is the fact that Swap( ref x, ref x ) will NOT do what the method's name implies (it will zero out the value, in fact).

提交回复
热议问题