Gray to Binary and Binary to Gray conversion | Helper function to xor two characters ; Helper function to flip the bit ; function to convert binary string to gray string ; MSB of gray code is same as binary code ; Compute remaining bits , next bit is computed by doing XOR of previous and current in Binary ; Concatenate XOR of previous bit with current bit ; function to convert gray code string to binary string ; MSB of binary code is same as gray code ; Compute remaining bits ; If current bit is 0 , concatenate previous bit ; Else , concatenate invert of previous bit ; Driver Code
def xor_c ( a , b ) : NEW_LINE INDENT return '0' if ( a == b ) else '1' ; NEW_LINE DEDENT def flip ( c ) : NEW_LINE INDENT return '1' if ( c == '0' ) else '0' ; NEW_LINE DEDENT def binarytoGray ( binary ) : NEW_LINE INDENT gray = " " ; NEW_LINE gray += binary [ 0 ] ; NEW_LINE for i in range ( 1 , len ( binary ) ) : NEW_LINE INDENT gray += xor_c ( binary [ i - 1 ] , binary [ i ] ) ; NEW_LINE DEDENT return gray ; NEW_LINE DEDENT def graytoBinary ( gray ) : NEW_LINE INDENT binary = " " ; NEW_LINE binary += gray [ 0 ] ; NEW_LINE for i in range ( 1 , len ( gray ) ) : NEW_LINE INDENT if ( gray [ i ] == '0' ) : NEW_LINE INDENT binary += binary [ i - 1 ] ; NEW_LINE DEDENT else : NEW_LINE INDENT binary += flip ( binary [ i - 1 ] ) ; NEW_LINE DEDENT DEDENT return binary ; NEW_LINE DEDENT binary = "01001" ; NEW_LINE print ( " Gray ▁ code ▁ of " , binary , " is " , binarytoGray ( binary ) ) ; NEW_LINE gray = "01101" ; NEW_LINE print ( " Binary ▁ code ▁ of " , gray , " is " , graytoBinary ( gray ) ) ; NEW_LINE