(((a +(b& 255))& 255)与((a + b)& 255)相同吗? [英] Is ((a + (b & 255)) & 255) the same as ((a + b) & 255)?
问题描述
我正在浏览一些C ++代码,发现了这样的内容:
I was browsing some C++ code, and found something like this:
(a + (b & 255)) & 255
双重加倍让我很烦,所以我想到了:
The double AND annoyed me, so I thought of:
(a + b) & 255
(a
和b
是32位无符号整数)
(a
and b
are 32-bit unsigned integers)
我迅速编写了一个测试脚本(JS)来确认我的理论:
I quickly wrote a test script (JS) to confirm my theory:
for (var i = 0; i < 100; i++) {
var a = Math.ceil(Math.random() * 0xFFFF),
b = Math.ceil(Math.random() * 0xFFFF);
var expr1 = (a + (b & 255)) & 255,
expr2 = (a + b) & 255;
if (expr1 != expr2) {
console.log("Numbers " + a + " and " + b + " mismatch!");
break;
}
}
尽管脚本证实了我的假设(两个操作都相等),但我仍然不相信它,因为1)随机和2)我不是数学家,我不知道我在做什么.
While the script confirmed my hypothesis (both operations are equal), I still don't trust it, because 1) random and 2) I'm not a mathematician, I have no idea what am I doing.
此外,对Lisp-y头衔感到抱歉.随时进行编辑.
Also, sorry for the Lisp-y title. Feel free to edit it.
推荐答案
它们是相同的.这是一个证明:
They are the same. Here's a proof:
首先记下身份(A + B) mod C = (A mod C + B mod C) mod C
让我们通过将a & 255
表示为a % 256
的代表来重述该问题.这是正确的,因为a
是无符号的.
Let's restate the problem by regarding a & 255
as standing in for a % 256
. This is true since a
is unsigned.
所以(a + (b & 255)) & 255
是(a + (b % 256)) % 256
这与(a % 256 + b % 256 % 256) % 256
相同(我已经应用了上述标识:请注意,mod
和%
对于无符号类型是等效的.)
This is the same as (a % 256 + b % 256 % 256) % 256
(I've applied the identity stated above: note that mod
and %
are equivalent for unsigned types.)
这简化为(a % 256 + b % 256) % 256
,它变为(a + b) % 256
(重新应用身份).然后,您可以将按位运算符放回给
This simplifies to (a % 256 + b % 256) % 256
which becomes (a + b) % 256
(reapplying the identity). You can then put the bitwise operator back to give
(a + b) & 255
完成证明.
这篇关于(((a +(b& 255))& 255)与((a + b)& 255)相同吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!