XOR变量交换如何工作?
有人可以向我解释XOR交换两个没有温度变量的变量如何工作?
void xorSwap (int *x, int *y)
{
if (x != y) {
*x ^= *y;
*y ^= *x;
*x ^= *y;
}
}
我了解它的作用,但是有人可以使我了解它的工作原理吗?
Can someone explain to me how XOR swapping of two variables with no temp variable works?
void xorSwap (int *x, int *y)
{
if (x != y) {
*x ^= *y;
*y ^= *x;
*x ^= *y;
}
}
I understand WHAT it does, but can someone walk me through the logic of how it works?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(12)
您可以通过进行替换来查看它的工作方式:
替换,
因为Xor是完全关联的和交换的:
因为
x xor x == 0
for任何x,以及
x xor 0 == x
对于任何X,并且交换完成。
You can see how it works by doing the substitution:
Substituting,
Because xor is fully associative and commutative:
Since
x xor x == 0
for any x,And since
x xor 0 == x
for any x,And the swap is done.
其他人已经解释了这一点,现在我想解释为什么 是一个好主意,但是现在不是。
早在我们拥有简单的单个周期或多循环CPU的那一天,使用此技巧来避免昂贵的内存消耗或溢出到堆栈中,便宜了。但是,现在我们拥有带有大量管道的CPU。 P4的管道范围从其管道中的20到31(大约)阶段,在这些阶段中,阅读和写入寄存器之间的任何依赖性都可能导致整个事情停滞不前。 XOR交换在A和B之间具有一些非常沉重的依赖性,实际上完全没有关系,但实际上在管道中拖延了管道。停滞的管道会导致慢速代码路径,如果此交换在您的内部循环中,您将非常缓慢地移动。
在一般实践中,您的编译器可以弄清楚当您与临时变量交换时,您真正想做的事情,并可以将其编译为单个 <> xchg 指令。使用XOR交换使编译器更难猜测您的意图,因此正确优化它的可能性要小得多。更不用说代码维护等。
Other people have explained it, now I want to explain why it was a good idea, BUT now isn't.
Back in the day when we had simple single cycle or multi-cycle CPUs, it was cheaper to use this trick to avoid costly memory dereferences or spilling registers to the stack. However, we now have CPUs with massive pipelines instead. The P4's pipeline ranged from having 20 to 31 (or so) stages in their pipelines, where any dependence between reading and writing to a register could cause the whole thing to stall. The xor swap has some very heavy dependencies between A and B that don't actually matter at all but stall the pipeline in practice. A stalled pipeline causes a slow code path, and if this swap's in your inner loop, you're going to be moving very slowly.
In general practice, your compiler can figure out what you really want to do when you do a swap with a temp variable and can compile it to a single XCHG instruction. Using the xor swap makes it much harder for the compiler to guess your intent and therefore much less likely to optimize it correctly. Not to mention code maintenance, etc.
我喜欢以图形方式而不是数字思考。
假设您从x = 11开始,y = 5
在二进制中(我要使用假设的4位机器),
现在是X和Y,XOR是一个反转操作,两次进行操作是一面镜子:
I like to think of it graphically rather than numerically.
Let's say you start with x = 11 and y = 5
In binary (and I'm going to use a hypothetical 4 bit machine), here's x and y
Now to me, XOR is an invert operation and doing it twice is a mirror:
这是一个应该更容易掌握的东西:
现在,可以将XOR技巧理解为^可以被认为是+>+>+ 或 - 。就像:
,所以:
Here's one that should be slightly easier to grok:
Now, one can understand the XOR trick a little more easily by understanding that ^ can be thought of as + or -. Just as:
, so:
它起作用的原因是因为XOR不会丢失信息。如果您可以忽略溢出,则可以使用普通的加法和减法来做同样的事情。例如,如果变量对A,B最初包含值1,2,则可以像这样交换它们:
顺便说一句,有一个旧的技巧用于编码单个“指针”中的2条链接列表。
假设您在地址A,B和C处有一个内存块列表。每个块中的第一个单词分别是:
如果您可以访问块A B中的“指针”并减去A,依此类推。它的工作也一样。要沿着列表运行,您需要将指针保持在两个连续的块上。当然,您将使用XOR代替加法/减法,因此您不必担心溢出。
如果您想玩一些乐趣,可以将其扩展到“链接的网络”。
The reason WHY it works is because XOR doesn't lose information. You could do the same thing with ordinary addition and subtraction if you could ignore overflow. For example, if the variable pair A,B originally contains the values 1,2, you could swap them like this:
BTW there's an old trick for encoding a 2-way linked list in a single "pointer".
Suppose you have a list of memory blocks at addresses A, B, and C. The first word in each block is , respectively:
If you have access to block A, it gives you the address of B. To get to C, you take the "pointer" in B and subtract A, and so on. It works just as well backwards. To run along the list, you need to keep pointers to two consecutive blocks. Of course you would use XOR in place of addition/subtration, so you wouldn't have to worry about overflow.
You could extend this to a "linked web" if you wanted to have some fun.
大多数人会使用临时变量交换两个变量x和y,例如:
这是一个简洁的编程技巧,可以交换两个值而不需要临时:
使用XOR交换两个变量
Most people would swap two variables x and y using a temporary variable, like this:
Here’s a neat programming trick to swap two values without needing a temp:
More details in Swap two variables using XOR
@vonc 正确,它是一个整洁的数学技巧。想象一下4个单词,看看这是否有帮助。
@VonC has it right, it's a neat mathematical trick. Imagine 4 bit words and see if this helps.
基本上XOR方法中有3个步骤:
A'= A Xor B(1)
b'= a'xor b(2)
a“ = a'xor b'(3)
了解 为什么 首先请注意:
一个步骤(1),A的二进制表示仅在A和B具有相对位的位位置的位置。那就是(AK = 1,BK = 0)或(AK = 0,BK = 1)。现在,当我们在步骤(2)中进行替换时,我们得到:
b'=(a xor b)xor b
= a xor(b xor b),因为xor是关联
= xor 0,因为上面的[4]
= a由于XOR的定义(请参阅 1 上面)
我们可以代替步骤(3):
a” =(a xor b)xor a
=(b xor a)xor a,因为xor是交换的
= b xor(a xor a),因为xor是关联
= b xor 0,因为[4]上方
= b由于XOR的定义(请参见 1 上面)
更多 )
更多详细信息此处:
必要且足够的
Basically there are 3 steps in the XOR approach:
a’ = a XOR b (1)
b’ = a’ XOR b (2)
a” = a’ XOR b’ (3)
To understand why this works first note that:
After Step (1), the binary representation of a will have 1-bits only in the bit positions where a and b have opposing bits. That is either (ak=1, bk=0) or (ak=0, bk=1). Now when we do the substitution in Step (2) we get:
b’ = (a XOR b) XOR b
= a XOR (b XOR b) because XOR is associative
= a XOR 0 because of [4] above
= a due to definition of XOR (see 1 above)
Now we can substitute into Step (3):
a” = (a XOR b) XOR a
= (b XOR a) XOR a because XOR is commutative
= b XOR (a XOR a) because XOR is associative
= b XOR 0 because of [4] above
= b due to definition of XOR (see 1 above)
More detailed information here:
Necessary and Sufficient
作为旁注,我几年前以交换整数的形式独立地重新发明了该轮子:(
上面以一种难以阅读的方式提到这一点),
完全相同的推理适用于XOR交换:a ^ b ^ b = a和a ^ b ^ a = a。由于Xor是可交换的,因此X ^ X = 0和X ^ 0 = X,因此这很容易看到
,
希望这会有所帮助。这种解释已经给出了...但不是很明显IMO。
As a side note I reinvented this wheel independently several years ago in the form of swapping integers by doing:
(This is mentioned above in a difficult to read way),
The exact same reasoning applies to xor swaps: a ^ b ^ b = a and a ^ b ^ a = a. Since xor is commutative, x ^ x = 0 and x ^ 0 = x, this is quite easy to see since
and
Hope this helps. This explanation has already been given... but not very clearly imo.
我只想添加数学解释,以使答案更加完整。在组理论,xor是 abelian group ,也称为通勤组。这意味着它满足五个要求:封闭,关联性,身份元素,逆元素,交换性。
XOR交换公式:
扩展公式,替换A,B具有先前公式:
交换性指的是“ A Xor B”等于“ B Xor A”:
arsisigiativity均表示“(A XOR B)XOR C”等于Xor(B Xor)(b xor) c)“:
XOR中的反元素本身,这意味着任何具有本身的值XOR给出了零:
XOR中的身份元素为零,这意味着任何具有零值的值XOR都不会变化:
您可以在中获取更多信息 。 组理论。
I just want to add a mathematical explanation to make the answer more complete. In group theory, XOR is an abelian group, also called a commutative group. It means it satisfies five requirements: Closure, Associativity, Identity element, Inverse element, Commutativity.
XOR swap formula:
Expand the formula, substitute a, b with previous formula:
Commutativity means "a XOR b" equal to "b XOR a":
Associativity means "(a XOR b) XOR c" equal to "a XOR (b XOR c)":
The inverse element in XOR is itself, it means that any value XOR with itself gives zero:
The identity element in XOR is zero, it means that any value XOR with zero is left unchanged:
And you can get further information in group theory.
我知道这个问题已经有很长时间了,有很多答案。但是,我有自己的“语言”技巧来理解位于位的魔法。也许对于某人而言,这将很有用。
XOR仅在其操作数中的一个是1而另一个是零时产生1的。因此,XOR是两个数字之间的差异。
*X ^= *y;
我们将此差异存储在x中。*y ^= *x;
找到第一个数字,*x ^= *y;
找到第二个数字
第一个数字,我们 必须尝试想象我脑海中的很多数字。这就是为什么我的回答中没有数值表示的原因。
I know the question has been asked for quite some time and there are many answers to it. However, I have my own "linguistic" trick for understanding bitwise magic. Perhaps for someone it will be useful.
XOR will only produce 1 if exactly one of its operands is 1 and the other is zero. Therefore XOR is the difference between two numbers.
*x ^= *y;
we store this difference in x.*y ^= *x;
*x ^= *y;
I'm having trouble translating into English, so I'll add a graphical representation:
I use this so I don't have to try to imagine a lot of numbers in my head. That is why there is no numerical representation in my answer.
其他人已经发布了解释,但我认为如果伴随一个很好的例子,最好理解。
xor真实
表和
b = 0101
我们能够以这样的方式交换值:Others have posted explanations but I think it would be better understood if its accompanied with a good example.
XOR Truth Table
If we consider the above truth table and take the values
A = 1100
andB = 0101
we are able to swap the values as such: