Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking even or odd `1` bits in a number

I want to check if number has all even or odd bits set to one and only them. For eg.:

Number 42 is correct, because in a binary code 101010 it has all and only even bits sets to 1. Number 21 is also correct, 10101.

Number 69 for eg. 1000101 is not correct, because there are only three odd bits sets to 1.

I've tried using different operations with ^, &, >>, << and i still have no idea how can i do this using these operators. Yes, i need to do this using logical operators in C.

like image 716
Mateusz Karwat Avatar asked Jan 16 '23 08:01

Mateusz Karwat


2 Answers

Those numbers have that property that (x ^ (x >> 1)) + 1 is a power of 2. And y is a power of 2 if y & (y - 1) == 0

So one test could be ((x ^ (x >> 1)) + 1) & (x ^ (x >> 1)) == 0 which would work for numbers of any size.

like image 161
Stephane Chazelas Avatar answered Jan 24 '23 15:01

Stephane Chazelas


#include <stdio.h>

int main(void)
{
    unsigned uu;

    for (uu=0; uu < 43; uu++ ) {
        int res;
        res = (((uu & 0xAAAAAAAA) == uu) || ((uu & 0x55555555) == uu) );
        printf("%u: %d\n", uu, res);
    }
    return 0;
}
like image 32
wildplasser Avatar answered Jan 24 '23 16:01

wildplasser