简体   繁体   English

c# 异或功能

[英]c# xor functionality

I found this code to reverse a string using the or operator,我发现这段代码使用 or 运算符反转字符串,

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?问题是我不明白 for 循环内部发生了什么,有人可以向我解释一下吗?

Thank you.谢谢你。

Here's how you can swap two values A, B without a temporary intermediate variable:以下是在没有临时中间变量的情况下交换两个值 A、B 的方法:

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

Ref: XOR swap algorithm参考:异或交换算法

Here's a 8 bit example:这是一个 8 位示例:

A = 10010010
B = 01111001

A = A Xor B = 11101011
B = A Xor B = 10010010
A = A Xor B = 01111001

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.它仅用于创建新变量“ temp ”来进行交换。

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.看看它正在使用一些 boolean 逻辑做什么。

It's the infamous XOR swap algorithm .这是臭名昭著的异或交换算法

The following exchanges the values of X and Y :下面交换XY的值:

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

See Wikipedia the article for details.有关详细信息,请参阅 Wikipedia 文章。

It's a bit of trickery.这有点诡计。 The XOR operator can be used as a bit mask to temporarily combine two values. XOR 运算符可用作位掩码来临时组合两个值。 XOR-ing X twice against Y will give Y. You can prove this easily with truth tables. XOR-ing X 与 Y 两次将得到 Y。您可以使用真值表轻松证明这一点。

In this case, the XOR is being used as a swap.在这种情况下,XOR 被用作交换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM