((a + (b & 255)) & 255) 和 ((a + b) & 255) 一样吗?

Is ((a + (b amp; 255)) amp; 255) the same as ((a + b) amp; 255)?(((a + (b amp; 255)) amp; 255) 和 ((a + b) amp; 255) 一样吗?)
本文介绍了((a + (b & 255)) & 255) 和 ((a + b) & 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

(ab 是 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 &amp; 255)) &amp; 255) 和 ((a + b) &amp; 255) 一样吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)