I am having trouble with the last problem of my bit twiddling homework exercise. The function is supposed to return 1 if any odd bit is set to 1.
Here is what I have so far:
int anyOddBit(int x) {
return (x & 0xaaaaaaaa) != 0;
}
That works perfectly, but I am not allowed to use a constant that large (only allowed 0 through 255, 0xFF). I am also not allowed to use !=
Specifically, this is what I am limited to using:
Each "Expr" is an expression using ONLY the following:
1. Integer constants 0 through 255 (0xFF), inclusive. You are
not allowed to use big constants such as 0xffffffff.
2. Function arguments and local variables (no global variables).
3. Unary integer operations ! ~
4. Binary integer operations & ^ | + << >>
I can’t figure out how to do this within in those restrictions and I’d really appreciate it if someone could point me in the right direction. Thanks in advance!
You can use:
The “inner” bit, which ORs together each source octet, will give you an octet where each bit is set if the equivalent bit is set in any of the source octets. So, if one of the odd bits is set in the source octets, it will also be set in the target one.
Then, by simply ANDing that with
0xaa, you get a zero value if no odd bits are set, or a non-zero value if any of the odd bits are set.Then, since you need 0 or 1, and you can’t use
!=, you can acheive a similar effect with!!, two logical not operators. It works because!(any-non-zero-value)gives0and!0gives1.In order to do it with 12 operators only (rather than 13 as per my original solution above), you can remove the
& 0xfffor the>> 24value since it’s not actually necessary (zero-bits are shifted in from the left):In fact, you can do even better than that. The final
& 0xaawill clear out all the upper 24 bits anyway so no& 0xffsections are needed (it also fits on one line as well):That gets it down to nine operators.