Is ((a + (b amp; 255)) amp; 255) the same as ((a + b) amp; 255)?(((a + (b amp; 255)) amp; 255) 和 ((a + b) amp; 255) 一样吗?)
问题描述
我正在浏览一些 C++ 代码,发现如下内容:
I was browsing some C++ code, and found something like this:
(a + (b & 255)) & 255
双重AND惹恼了我,所以我想到了:
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) 一样吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:((a + (b & 255)) & 255) 和 ((a + b) & 255) 一样吗?


基础教程推荐
- 设计字符串本地化的最佳方法 2022-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- C++,'if' 表达式中的变量声明 2021-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01