I can only use the bitwise operators mentioned below to create the described function:
/*
* allEvenBits - return 1 if all even-numbered bits in word set to 1
* Examples allEvenBits(0xFFFFFFFE) = 0, allEvenBits(0x55555555) = 1
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 12
* Rating: 2
*/
We use a 2s complement, 32-bit integer representations. In addition, I can only use integer constants from 0 to 255 (0xFF) inclusive. My rude decision is this:
int allEvenBits(int x) {
int mask0 = 0x55;
int mask1 = 0x55 << 8;
int mask2 = 0x55 << 16;
int mask3 = 0x55 << 24;
return(!(x ^ (mask0 | mask1 | mask2 | mask3)));
}
So, I basically created the mask 0x55555555, XOR the mask with int x and deny this operation, assuming the only time (x ^ 0x55555555) is 0 if x is 0x55555555. (Based on the XOR property, that x ^ x == 0.)
Therefore, when int x = 0x55555555, this should be the only moment when my function returns 1. And it returns 1 when int x = 0x55555555.
, , . ?