ygdytdh
ygdytdh

Reputation: 53

c# xor functionality

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.

Upvotes: 5

Views: 2607

Answers (5)

Mitch Wheat
Mitch Wheat

Reputation: 300827

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

Upvotes: 5

Jalal Said
Jalal Said

Reputation: 16162

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.

Upvotes: 3

harpo
harpo

Reputation: 43228

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.

Upvotes: 0

Brett Walker
Brett Walker

Reputation: 3586

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.

Upvotes: 1

Mat
Mat

Reputation: 206909

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.

Upvotes: 0

Related Questions