5

I found this code to reverse a string using the or operator,

public static string ReverseXor(string s)
{

      if (s == null) return null; 
      char[] charArray = s.ToCharArray(); 
      int len = s.Length - 1;

      for (int i = 0; i < len; i++, len--)
      { 
            charArray[i] ^= charArray[len]; 
            charArray[len] ^= charArray[i]; 
            charArray[i] ^= charArray[len]; }

       //some more code
}

The problem is I'm not understand in what's happening inside the for loop, can someone explain this to me?

Thank you.

Quintin Robinson
  • 81,193
  • 14
  • 123
  • 132
ygdytdh
  • 53
  • 1
  • 3
  • Original function is [here](http://stackoverflow.com/questions/228038/best-way-to-reverse-a-string-in-c-2-0/228062#228062) – yakatz Aug 14 '11 at 06:05

5 Answers5

5

Here's how you can swap two values A, B without a temporary intermediate variable:

A = A Xor B
B = A Xor B
A = A Xor B

Ref: XOR swap algorithm

Here's a 8 bit example:

A = 10010010
B = 01111001

A = A Xor B = 11101011
B = A Xor B = 10010010
A = A Xor B = 01111001
Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
  • Thanks for the bitwise explanation, how does it work on swapping characters, could you explain that? – ygdytdh Aug 15 '11 at 06:02
  • You can use XOR swap for any number of bits (8, 16, 32, 64 being the usual suspects): you can even use it to swap pointers. It's all just bits... – Mitch Wheat Aug 15 '11 at 06:04
3

The method uses "old trick" to swap variables that is all, it is equals to:

char temp = charArray[i];
charArray[i] = charArray[len];
charArray[len] = temp;

It is used to just elemenate the creation of new variable "temp" to do the swap.

Jalal Said
  • 15,906
  • 7
  • 45
  • 68
  • 1
    Which is by the way not faster than using a temporary in almost any scenario. – Tim Dec 03 '13 at 19:56
1

The way to look at this, I think, is in two parts. What is the loop doing? And what is the inner part of the loop doing?

The loop is looking at the ends of the string, which pregresively move inwards towards the center.

The inner part of the loop is doing an xor swap. This is a trick to swap two variables without a third variable. Look at whet it is doing using some boolean logic.

Brett Walker
  • 3,566
  • 1
  • 18
  • 36
0

It's the infamous XOR swap algorithm.

The following exchanges the values of X and Y:

X := X XOR Y
Y := X XOR Y
X := X XOR Y

See Wikipedia the article for details.

Mat
  • 202,337
  • 40
  • 393
  • 406
0

It's a bit of trickery. The XOR operator can be used as a bit mask to temporarily combine two values. XOR-ing X twice against Y will give Y. You can prove this easily with truth tables.

In this case, the XOR is being used as a swap.

harpo
  • 41,820
  • 13
  • 96
  • 131