Compute the parity of a number using XOR and table look | CPP program to illustrate Compute the parity of a number using XOR ; Generating the look - up table while pre - processing ; LOOK_UP is the macro expansion to generate the table ; Function to find the parity ; Number is considered to be of 32 bits ; Dividing the number into 8 - bit chunks while performing X - OR ; Masking the number with 0xff ( 11111111 ) to produce valid 8 - bit result ; Driver code ; Result is 1 for odd parity , 0 for even parity ; Printing the desired result
#include <bits/stdc++.h> NEW_LINE #define P2 ( n )  n, n ^ 1, n ^ 1, n NEW_LINE #define P4 ( n )  P2(n), P2(n ^ 1), P2(n ^ 1), P2(n) NEW_LINE #define P6 ( n )  P4(n), P4(n ^ 1), P4(n ^ 1), P4(n) NEW_LINE #define LOOK_UP  P6(0), P6(1), P6(1), P6(0) NEW_LINE unsigned int table [ 256 ] = { LOOK_UP } ; int Parity ( int num ) { int max = 16 ; while ( max >= 8 ) { num = num ^ ( num >> max ) ; max = max / 2 ; } return table [ num & 0xff ] ; } int main ( ) { unsigned int num = 1742346774 ; bool result = Parity ( num ) ; result ? std :: cout << " Odd ▁ Parity " : std :: cout << " Even ▁ Parity " ; return 0 ; }