正如 Dukelings 的回答和 CmdrMoozy 的评论所示,这并不总是正确的。从你的帖子来看,至少是真的有时。那么这里就稍微详细一点的分析一下。
The +
-side
显然,如果(但不仅仅是如果)(x & y) == 0
then (x ^ y) == x + y
, 因为
x + y = (x ^ y) + ((x & y) << 1)
That accounts for 332 cases (for every bit position, there are 3 choices that result in a 0 after the AND) where (x ^ y) == (x + y)
.
然后还有一些情况(x & y) != 0
。这些案例正是这样的案例
(x & y) == 0x80000000
,因为最高位的进位是唯一不影响任何内容的进位。
That adds 331 cases (for 31 bit positions there are 3 choices, for the highest bit there is only 1 choice).
The -
-side
对于减法,有一个鲜为人知的恒等式x - y == (x ^ y) - ((~x & y) << 1)
.
That's really not too different from addition, and the analysis almost the same. This time, if (but not only if) (~x & y) == 0
then (x ^ y) == x - y
. That ~
doesn't change the number of cases: still 332. Most of them are different cases than before, but not all (consider y = 0
, then x
can be anything).
There are again 331 extra cases, this time from (~x & y) == 0x80000000
.
双方
The +
and -
双方并不脱节。有时,x ^ y = x + y = x - y
。这只有在以下任一情况下才会发生y = 0
or y = 0x80000000
. If y = 0
, x
可以是任何东西,因为(x & 0) == 0
and (~x & 0) == 0
对全部x
. If y = 0x80000000
, x
又可以是任何东西,这次是因为x & 0x80000000
and ~x & 0x80000000
两者都可以算出 0 或0x80000000
,两者都很好。
That gives 233 cases where x ^ y = x + y = x - y
.
It also gives (332 + 331) * 2 - 233 cases where x ^ y
is x + y
or x - y
or both, which is 4941378580336984 or in base 16, 118e285afb5158, which is also the answer given by this site.
That's a lot of cases, but only roughly 0.02679% of the total space of 264.