0

I'm trying to do bit logic manipulation in C but getting stuck. I need to write a function that, given an input argument it will evaluate if my argument has all even bits set to 1. For example:

myFunction (0xFFFFFFFE) = 0;
myFunction (0x55555555) = 1;

The operators that I'm permitted to use are: ! ~ & ^ | + << >>. I can't use if statements, loops, or equality checks (so no == or != operators).

4

3 回答 3

6

您需要使用掩码测试该值,并且对如何在不使用 的情况下测试相等性有点迂回==,例如:

return !((n & 0x55555555) ^ 0x55555555);

注意:这假定为 32 位值。

于 2013-02-01T06:56:18.020 回答
4

由于不允许使用“==”,因此必须使用其他技巧:

 (~number & 0x55555555) will be zero only when number&mask == mask.
 (~number & 0x55555555)==0 OTOH codes as 

 return !(~number & 0x55555555);
于 2013-02-01T07:01:33.483 回答
0

这就是你如何使用 C 编程来解决它,而不会对你自己施加任何奇怪的人为限制:

// Get a platform-independent mask of all even bits in an int set to one:
#define MASK ( (unsigned int) 0x55555555u )

// MASK will be 0x5555u or 0x55555555u depending on sizeof(int).

然后是实际的算法:

if((x & MASK) == MASK)
于 2013-02-01T07:40:50.497 回答