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
function xor_c ( a , b ) { return ( a == b ) ? ' ' : ' ' ; } function flip ( c ) { return ( c == ' ' ) ? ' ' : ' ' ; } function binarytoGray ( binary ) { let gray = " " ; gray += binary [ 0 ] ; for ( let i = 1 ; i < binary . length ; i ++ ) { gray += xor_c ( binary [ i - 1 ] , binary [ i ] ) ; } return gray ; } function graytoBinary ( gray ) { let binary = " " ; binary += gray [ 0 ] ; for ( let i = 1 ; i < gray . length ; i ++ ) { if ( gray [ i ] == ' ' ) binary += binary [ i - 1 ] ; else binary += flip ( binary [ i - 1 ] ) ; } return binary ; } let binary = " " ; document . write ( " " + binary + " " + binarytoGray ( binary ) + " " ) ; let gray = " " ; document . write ( " " + gray + " " + graytoBinary ( gray ) ) ;