Arduino 和 Bitwise,意想不到的结果
在这里让我自己有点困惑。
我想测试一组位(3 位)是否包含某个位置的位。
if (B110 & B010 == B010)
(B110 是要检查的数字,B010 是我想查看是否存在的位)
上面的代码没有给我预期的结果,B110 都是 true,B101 都是 true。我非常确定我需要使用 &(and) 来测试掩码 B010。
我的理解是B110& B010 等于 B010,并且 B101 和 B101 等于 B010。 B010 等于 B000。但是我的 if 语句是使用两个测试位运行的吗?
我正在 Arduino 中编码,我确信这对我来说是一个简单的误解,但不确定在哪里。
Getting my self a bit confused here.
I would like to test if a set of bits (3 bits) contains a bit in a certain postion.
if (B110 & B010 == B010)
(B110 being the number to check, B010 the bit I want to see if is there)
The above code isn't giving me the expected out come, both B110 is true and B101 is true. I am pretty sure that I need to use a &(and) to test with the mask B010.
My understanding is that B110 & B010 would be equal to B010 and that B101 & B010 would equal B000. But my if statement is run with both test bits?
I am coding in an Arduino, I'm sure that it's a simple misunderstanding on my behalf but not sure where.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试
if ((B110 & B010) == B010)
目前它运行为
if (B110 & (B010 == B010))
这将始终为 true 。正如此表所示,==和! = 的优先级高于 &、| 等。
Try
if ((B110 & B010) == B010)
At the moment it's running as
if (B110 & (B010 == B010))
which will always be true.As this table shows, == and != have a higher precedence than &, | etc.
在这个测试中,“
== B010
”实际上是不必要的。在 C 中,0
表示“假”,而任何非零值都被视为“真”。B110 & B010
(或设置了该位的任何其他值)将返回B010
,它不等于0
,因此测试成功。The "
== B010
" is actually unnecessary in this test. In C,0
represents "false," while any nonzero value is considered "true."B110 & B010
(or any other value with that bit set) will returnB010
, which is not equal to0
, so the test succeeds.