bit manipulation C allEvenBits

0

I have to use bitwise manipulations to accomplish something. This is what the question asks of me:

/* 
 * 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
 */

This is what I've worked out:

int allEvenBits(int x) {
int y, z, p, q, r, s, t, u, k;
y=x;
z=y&0x5555;
y>>16;
p=y&z;
q=p&0x055;
p>>8;
r=q&p;
s=r&0x05;
r>>4;
t=s&r;
u=t&0x01;
t>>2;
k=u&t;
return k;
}

But everytime I run this to test whether the function holds for all possible values of 32 bit integers, I get this error message:

ERROR: Test allEvenBits(-2147483647[0x80000001]) failed...

...Gives 1[0x1]. Should be 0[0x0]

This, even though I'm ANDing all the even bits at each stage, so theres no way I would get the function to return a 1 when the final manipulation yeilds a 0. I tried math with a smaller 8 bit number of a similar form, it gives the right answer, so I don't understand what is happening wrong with this implementation.

c
bit-manipulation
asked on Stack Overflow Jan 25, 2015 by stalagmite7 • edited Jun 20, 2020 by Community

2 Answers

1

Your statements such as

y>>16;

lack an = sign and so have no effect, try

y>>=16;
...
p>>=8;
...
r>>=4;
...
t>>=2;

Also, declare as unsigned int as recommended by @abligh.

answered on Stack Overflow Jan 25, 2015 by Weather Vane • edited Jan 25, 2015 by Weather Vane
0

Do not shift signed integers right. It is undefined behaviour in C. You will (probably) be sign-extending from the left. Try with unsigned int.

answered on Stack Overflow Jan 25, 2015 by abligh

User contributions licensed under CC BY-SA 3.0