/*************************************************** Name: check_parity.c Copyright: kernelxu,Mike Wahler,Joe Wright Author: kernelxu Date: 29-08-05 12:10 Description: parity check of an unsigned integer Compiler: WIN2000+DEV-C++4.9.9.2 My E_mail: kernelxu@hotmail.com source: http://groups.google.com/group/comp.lang.c/ browse_thread/thread/25bc2430a2ca06f5/ 295c349ec797b3c0?hl=en#295c349ec797b3c0 ****************************************************/ #include <limits.h> #include <stdio.h> unsigned int bits1(unsigned int value); unsigned int bits2(unsigned int value); unsigned int even(unsigned int value); unsigned int odd(unsigned int value); unsigned int odd_even(unsigned value); int main(void) { const char *parity[] = {"ODD", "EVEN"}; /*excellent!*/ unsigned int i = 0; puts("Value Bits Parity"); for(; i < 20; ++i) printf("%5u %4u %s\n", i, bits1(i), parity[even(i)]);
system("pause"); return 0; } unsigned int bits1(unsigned int value) { unsigned int n = 0;
while (value) { value &= (value - 1); /*more efficient than bits2()*/ /* less loops*/ ++n; } return n; } unsigned int bits2(unsigned int value) { unsigned int result = 0; unsigned int mask = 1; while(mask) { result += (value & mask) != 0; /*count the number of '1'*/ mask *= 2; /*equal to "mask <<= 1;"*/ } return result; } unsigned int even(unsigned int value) { return !(bits1(value) % 2);
} unsigned int odd(unsigned int value) { return !even(value); } unsigned int odd_even(unsigned value) { return !(0x01 & value); /*return 0 value is odd; */ /*return 1 value is even*/ }
|