Gray to Binary and Binary to Gray conversion | C # program for Binary To Gray and Gray to Binary 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 program to test above functions
using System ; class GFG { static char xor_c ( char a , char b ) { return ( a == b ) ? '0' : '1' ; } static char flip ( char c ) { return ( c == '0' ) ? '1' : '0' ; } static String binarytoGray ( String binary ) { String gray = " " ; gray += binary [ 0 ] ; for ( int i = 1 ; i < binary . Length ; i ++ ) { gray += xor_c ( binary [ i - 1 ] , binary [ i ] ) ; } return gray ; } static String graytoBinary ( String gray ) { String binary = " " ; binary += gray [ 0 ] ; for ( int i = 1 ; i < gray . Length ; i ++ ) { if ( gray [ i ] == '0' ) binary += binary [ i - 1 ] ; else binary += flip ( binary [ i - 1 ] ) ; } return binary ; } public static void Main ( ) { String binary = "01001" ; Console . WriteLine ( " Gray ▁ code ▁ of ▁ " + binary + " ▁ is ▁ " + binarytoGray ( binary ) ) ; String gray = "01101" ; Console . Write ( " Binary ▁ code ▁ of ▁ " + gray + " ▁ is ▁ " + graytoBinary ( gray ) ) ; } }