对两位以上使用按位 AND

发布于 2024-09-02 17:32:40 字数 307 浏览 3 评论 0原文

我对按位运算符还很陌生。假设我有 3 个变量 abc,这些值是二进制的:

  a = 0001
  b = 0011
  c = 1011

现在,我想像这样执行按位 AND :

    a
AND b
AND c
--------
d = 0001

d &= a &= b &= c 不起作用(如我所料),但我该怎么做? 谢谢

I am pretty new to bitwise operators. Let's say I have 3 variables a, b and c, with these values in binary:

  a = 0001
  b = 0011
  c = 1011

Now, I want to perform a bitwise AND like this:

    a
AND b
AND c
--------
d = 0001

d &= a &= b &= c doesn't work (as I expected), but how can I do this?
Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

倾其所爱 2024-09-09 17:32:40

光是这个有什么问题呢。

d = a & b & c;

What's wrong with just this.

d = a & b & c;
最丧也最甜 2024-09-09 17:32:40

您想要:

d = a & b & c;

&= 表示按位与并且还进行赋值。

如果 d 最初被指定为 0,那么您所输入的表达式将始终计算为 0,因为任何 & 0 code> 将等于 0

You want:

d = a & b & c;

&= means bitwise AND and also assign.

If d was originally assinged to be 0 your expression as you put it would always evaluate to 0 because anything & 0 will equal 0.

欲拥i 2024-09-09 17:32:40

这应该有效

int a = 1;  // 0001
int b = 3;  // 0011
int c = 11; // 1011
int d = 0;

d = a & b & c;

this should work

int a = 1;  // 0001
int b = 3;  // 0011
int c = 11; // 1011
int d = 0;

d = a & b & c;
夏末染殇 2024-09-09 17:32:40

您可能只是忘记将“d”初始化为全 1,并且默认为 0。您可以通过分配 d=-1 轻松将所有位设置为 1,或者如果您愿意,则 d=0xffffffff,尽管因为您只是使用 4 位,d=0xF 就足够了。

话虽这么说,像这样的菊花链操作符往往比其他人建议的分解操作更难读。

You probably just forgot to initialize 'd' to being all 1's, and it defaulted to 0. You can easily set all the bits to 1 by assigning d=-1, or if you prefer, d=0xffffffff, although since you were only using 4 bits, d=0xF would have sufficed.

That being said, daisy-chaining operators like that tends to be less readable than breaking things out as others have suggested.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文