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
#include <iostream> NEW_LINE using namespace std ; 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 [ 0 ] ; for ( int i = 1 ; i < binary . length ( ) ; i ++ ) { gray += xor_c ( binary [ i - 1 ] , binary [ i ] ) ; } return gray ; } 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 ; } int main ( ) { string binary = "01001" ; cout << " Gray ▁ code ▁ of ▁ " << binary << " ▁ is ▁ " << binarytoGray ( binary ) << endl ; string gray = "01101" ; cout << " Binary ▁ code ▁ of ▁ " << gray << " ▁ is ▁ " << graytoBinary ( gray ) << endl ; return 0 ; }