15 September 2009

parity in C

int oparity(int val)
{
int parity = 0;

while(val)
{
parity = !parity;
val &= val-1;
//val = val&(val-1);
//val &= ~(val&-val);
//val ^= val&(~val+1);
}

return parity;
}

int oparity(int val)
{
int nbit = 0;

while(val)
{
if(val&1) nbit++;
val >>= 1;
}

return nbit%2;
}

-----------------oddparity.c-----------------
#include <stdio.h>

int oparity(int val)
{
int nbit = 0;

while(val)
{
if(val&1) nbit++;
val >>= 1;
}

return nbit%2;
}

int main()
{
int val = 0xaF19;

printf("oddparity of 0x%X is %d\n", val, oparity(val));
printf("evenparity of 0x%X is %d\n", val, oparity(val)?0:1);

return 0;
}
---------------------------------------------

Reference:
http://resnet.uoregon.edu/~gurney_j/jmpc/bitwise.html

No comments:

Post a Comment