作者: Note 分类: php框架与应用 发布时间: 2016-01-07 16:09

Attributed to Solomon W. Golomb; a method for swapping the values of two integer variables without using an intermediate variable (you can tell this dates from the Elder Days, when variables were expensive!). Thanks to PHP‘s syntax it’s also a one-liner.
Okay, here’s how it goes (yeah, like I need to make content-free posts just for the sake of an increment…NoteBlog).
First, simplify the line; noting that ^= is right-associative, which means that in that line the rightmost operator is evaluated first, that the assignment operators also return the value that they assign to their lvalue, and that foo^=bar is shorthand for foo=foo^bar:



Recall what ^ does. Takes each pair of corresponding bits from its arguments (the internal binary representation of its arguments, that is), and xors them together to produce the corresponding bit of the result (“corresponding” means that the first bits of both arguments produce the first bit of the result, the second bits of both arguments produce the second bit of the result, and so on. This is why, as BuzzLY noted, it’s important that both variables are the same size – demons probably start flying out of your nose if one of them runs out of bits to xor before the other. So to figure out what ^ does to a pair of variables, we only need to recap what it does to single bits



电子邮件地址不会被公开。 必填项已用*标注

6 + = 13