Compute the parity of a number using XOR and table look | 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 o 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
def P2 ( n , table ) : NEW_LINE INDENT table . extend ( [ n , n ^ 1 , n ^ 1 , n ] ) NEW_LINE DEDENT def P4 ( n , table ) : NEW_LINE INDENT return ( P2 ( n , table ) , P2 ( n ^ 1 , table ) , P2 ( n ^ 1 , table ) , P2 ( n , table ) ) NEW_LINE DEDENT def P6 ( n , table ) : NEW_LINE INDENT return ( P4 ( n , table ) , P4 ( n ^ 1 , table ) , P4 ( n ^ 1 , table ) , P4 ( n , table ) ) NEW_LINE DEDENT def LOOK_UP ( table ) : NEW_LINE INDENT return ( P6 ( 0 , table ) , P6 ( 1 , table ) , P6 ( 1 , table ) , P6 ( 0 , table ) ) NEW_LINE DEDENT table = [ 0 ] * 256 NEW_LINE LOOK_UP ( table ) NEW_LINE def Parity ( num ) : NEW_LINE INDENT max = 16 NEW_LINE while ( max >= 8 ) : NEW_LINE INDENT num = num ^ ( num >> max ) NEW_LINE max = max // 2 NEW_LINE DEDENT return table [ num & 0xff ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT num = 1742346774 NEW_LINE result = Parity ( num ) NEW_LINE print ( " Odd ▁ Parity " ) if result else print ( " Even ▁ Parity " ) NEW_LINE DEDENT