C 使用按位运算符判断二进制数是否所有偶数都设置为 0
可能的重复:
查找是否每个偶数位都设置为0 使用按位运算符
另一个例子并没有真正回答我的问题,所以情况如下:
如果位序列中的所有偶数都设置为 0,我需要返回 1,否则返回 0。 -我不能使用条件语句!
所以我有一个数字 0x7f (01111111)
我可以通过 0xAA(10101010) 的掩码
给我: 00101010
我只需要做 0 或 1 所以我 !!(00101010) 这会给我布尔值但它返回 1,但我需要 0,这样我就可以否定它或使用不同的掩码。
我一直在循环这个问题,它让我发疯,请帮助并记住没有条件语句只有这些运算符:
! 〜& ^ | + << >>>
Possible Duplicate:
Find if every even bit is set to 0 using bitwise operators
The other example didnt really answer my question so here is the situation:
I need to return 1 if all evens in the bit sequence are set to 0 and return 0 otherwise.
-I cant use conditional statements!
So I have a number 0x7f (01111111)
I can and by a mask of 0xAA(10101010)
that gives me: 00101010
I need to do only a 0 or 1 so I !!(00101010) and that will give me the boolean value for it but it returns a 1 but I need a 0 so I can negate it or use a different mask.
I keep going in circles with this and its driving me nuts please help and remember no conditional statements just these operators:
! ~ & ^ | + << >>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我错过了什么吗?结果是
00101010
,所以并非所有偶数都是 0。在这种情况下,您应该返回 0,但是您!!
(两次否定)的结果。为什么呢?非零值被否定为 false,然后被否定为 true,即 1...与您需要的相反...反之亦然:对于 0x15 (00010101),所有偶数都是 0,与0xAA 给出 0,否定给出 true,再次否定给出 false,结果为 0...
Am I missing something? You get
00101010
as a result, so not all evens are 0. in that case you should return 0, but you!!
(twice negate) the result. Why that? The non-zero value is negated to false, which is then negated to true, which is 1... Just the opposite of what you need...Other way round: with 0x15 (00010101), all evens are 0, ANDing with 0xAA gives 0, negated gives true, again negated gives false, result is 0...
(~(2^1 & 你的号码)) & (~(2^3 & yournumber)) 等一直向下就可以了。不确定这是否是最快的方法 (~(2^1 & yournumber)) & (~(2^3 & yournumber)) 等一直向下就可以了。但不确定这是否是最快的方法 - 您可以创建一个函数来循环并使其继续执行可配置的位数。
(~(2^1 & yournumber)) & (~(2^3 & yournumber)), etc all the way down would work. Not sure if its the fastest way though (~(2^1 & yournumber)) & (~(2^3 & yournumber)), etc all the way down would work. Not sure if its the fastest way though - and you could make a function to cycle through and make it go on for a configurable number of bits.