开发者

C Using bitwise operators tell if binary number has all evens set to 0 [duplicate]

This question already has answers here: Closed 11 years ago.

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开发者_JAVA百科 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:

! ~ & ^ | + << >>


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 & 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜