C - Using bitwise operators to determine if all even bits are set to 1


Hi I am having trouble getting this function to work. Basically, the the function should return a 1 if all even place bits are 1 and 0 otherwise. This program always prints 0 for some reason.

Here is the code :

#include <stdio.h>

int allEvenBits(int);

int main() {
        printf("%d\n", allEvenBits(0xFFFFFFFE));
        return 0;

int allEvenBits(int X) {
        return !((X & 0x55555555) ^ 0x55555555);
asked on Stack Overflow Sep 16, 2014 by mrQWERTY

1 Answer


You are checking the odd bits for the even should be with 0xAAAAAAAA:

const unsigned int ODD_BITS_SET = 0x55555555;
const unsigned int EVEN_BITS_SET = 0xAAAAAAAA;
unsigned int allOddBits(unsigned int X) { return (X & ODD_BITS_SET) == ODD_BITS_SET; }
unsigned int allEvenBits(unsigned int X) { return (X & EVEN_BITS_SET) == EVEN_BITS_SET; }

Better to give a name to the magic number.

answered on Stack Overflow Sep 16, 2014 by NetVipeC • edited Sep 16, 2014 by NetVipeC

User contributions licensed under CC BY-SA 3.0