mrQWERTY
mrQWERTY

Reputation: 4149

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);
}

Upvotes: 1

Views: 2893

Answers (1)

NetVipeC
NetVipeC

Reputation: 4432

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.

Upvotes: 8

Related Questions