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
< ? php function xor_c ( $ a , $ b ) { return ( $ a == $ b ) ? '0' : '1' ; } function flip ( $ c ) { return ( $ c == '0' ) ? '1' : '0' ; } function binarytoGray ( $ binary ) { $ gray = " " ; $ gray . = $ binary [ 0 ] ; for ( $ i = 1 ; $ i < strlen ( $ binary ) ; $ i ++ ) { $ gray . = xor_c ( $ binary [ $ i - 1 ] , $ binary [ $ i ] ) ; } return $ gray ; } function graytoBinary ( $ gray ) { $ binary = " " ; $ binary . = $ gray [ 0 ] ; for ( $ i = 1 ; $ i < strlen ( $ gray ) ; $ i ++ ) { if ( $ gray [ $ i ] == '0' ) $ binary . = $ binary [ $ i - 1 ] ; else $ binary . = flip ( $ binary [ $ i - 1 ] ) ; } return $ binary ; } $ binary = "01001" ; print ( " Gray ▁ code ▁ of ▁ " . $ binary . " ▁ is ▁ " . binarytoGray ( $ binary ) . " STRNEWLINE " ) ; $ gray = "01101" ; print ( " Binary ▁ code ▁ of ▁ " . $ gray . " ▁ is ▁ " . graytoBinary ( $ gray ) ) ; ? >