Gray to Binary and Binary to Gray conversion | Java 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
import java . io . * ; class code_conversion { char xor_c ( char a , char b ) { return ( a == b ) ? '0' : '1' ; } char flip ( char c ) { return ( c == '0' ) ? '1' : '0' ; } String binarytoGray ( String binary ) { String gray = " " ; gray += binary . charAt ( 0 ) ; for ( int i = 1 ; i < binary . length ( ) ; i ++ ) { gray += xor_c ( binary . charAt ( i - 1 ) , binary . charAt ( i ) ) ; } return gray ; } String graytoBinary ( String gray ) { String binary = " " ; binary += gray . charAt ( 0 ) ; for ( int i = 1 ; i < gray . length ( ) ; i ++ ) { if ( gray . charAt ( i ) == '0' ) binary += binary . charAt ( i - 1 ) ; else binary += flip ( binary . charAt ( i - 1 ) ) ; } return binary ; } public static void main ( String args [ ] ) throws IOException { code_conversion ob = new code_conversion ( ) ; String binary = "01001" ; System . out . println ( " Gray ▁ code ▁ of ▁ " + binary + " ▁ is ▁ " + ob . binarytoGray ( binary ) ) ; String gray = "01101" ; System . out . println ( " Binary ▁ code ▁ of ▁ " + gray + " ▁ is ▁ " + ob . graytoBinary ( gray ) ) ; } }