时间:2019-03-17 标签:c#xorfunction
我发现这段代码使用 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
}
问题是我不明白 for 循环内发生了什么,有人可以向我解释一下吗?
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
以下是如何在没有临时中间变量的情况下交换两个值 A、B:
参考:XOR 交换算法
这是一个 8 位示例:
Here's how you can swap two values A, B without a temporary intermediate variable:
Ref: XOR swap algorithm
Here's a 8 bit example:
该方法使用“老技巧”来交换变量,仅此而已,它等于:
它用于仅创建新变量“
temp
”来进行交换。The method uses "old trick" to swap variables that is all, it is equals to:
It is used to just elemenate the creation of new variable "
temp
" to do the swap.我认为看待这个问题的方式可以分为两部分。循环在做什么?循环的内部部分在做什么?
循环着眼于绳子的末端,绳子的末端预先向内移动到中心。
循环的内部部分正在执行异或交换。这是一个在没有第三个变量的情况下交换两个变量的技巧。使用一些布尔逻辑来查看它正在做什么。
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.
这是臭名昭著的异或交换算法。
下面交换
X
和Y
的值:详细信息请参见维基百科文章。
It's the infamous XOR swap algorithm.
The following exchanges the values of
X
andY
:See Wikipedia the article for details.
这有点诡计。 XOR 运算符可用作位掩码来临时组合两个值。 X 与 Y 进行异或两次将得到 Y。您可以使用真值表轻松证明这一点。
在这种情况下,异或被用作交换。
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.