Bitwise operations in C: I can not understand why XOR does not work. Is my code or logic wrong?

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.

, , . ?

+4
3

, 0. 1 , , , 1, 0. , 0s

return (!(x ^ (mask0 | mask1 | mask2 | mask3)));

int allEvenBits(int x) {
  int mask = 0x55;
  int mask = mask | (mask << 8);
  int mask = mask | (mask << 16);

  return !(x & mask);
}

int allEvenBits(int x) {
  int mask = 0xAA;
  int mask = mask | (mask << 8);
  int mask = mask | (mask << 16);

  return !((x | mask) ^ (~0));
}

x &= x >> 16;
x &= x >> 8;
return !((x & 0x55) ^ 0x55);
// or return !(((x | 0xAA) + 1) & 0xFF);
+1

, , 1 0x55555555, :

int allEvenBits(int x) {
  int filled = x | 0xAAAAAAAA;
  return !(filled + 1);
}

, . , , 0xFFFFFFFF. 0, , , , . , 0xFFFFFFFF, , 0.

+2
// 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).
   And then the actual algorithm: */
unsigned int allEvenBits(int x) 
{
  return (unsigned int)( !(x ^ MASK) );
}
0
source

All Articles