((a + (b & 255)) & 255) 和 ((a + b) & 255) 一样吗? [英] Is ((a + (b & 255)) & 255) the same as ((a + b) & 255)?

查看:25
本文介绍了((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) 一样吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆