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.
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.
#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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With