对两位以上使用按位 AND
我对按位运算符还很陌生。假设我有 3 个变量 a
、b
和 c
,这些值是二进制的:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
光是这个有什么问题呢。
What's wrong with just this.
您想要:
&=
表示按位与并且还进行赋值。如果
d
最初被指定为0
,那么您所输入的表达式将始终计算为 0,因为任何&
0
code> 将等于0
。You want:
&=
means bitwise AND and also assign.If
d
was originally assinged to be0
your expression as you put it would always evaluate to 0 because anything&
0
will equal0
.这应该有效
this should work
您可能只是忘记将“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.