C++ Program to Convert Gray Code to Binary Code

This C++ program which converts given Gray Code to Binary Code. Both the codes can be stored in a character string. The Binary Code is formed as follows: The most significant bit is same for both, the bit value of next position of Gray Code and previous Binary Code are XORed and stored in next position of Binary Code until we reach the end of Gray Code string.

Here is the source code of the C++ program which converts the given Gray Code to Binary Code. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to Convert Gray Code to Binary Code
  3.  */
  4.  
  5. #include <iostream>
  6. #include <string>
  7.  
  8. int main(int argc, char* argv[])
  9. {
  10.     std::string gray, binary;
  11.  
  12.     std::cout << "Enter the gray code ";
  13.     std::cin >> gray;
  14.     binary = gray[0];
  15.     for (int i = 0; i < gray.length() - 1; i++)
  16.     {
  17.         /* XOR operation */
  18.         if (binary[i] == gray[i+1])
  19.             binary = binary + "0";
  20.         else
  21.             binary = binary + "1";
  22.     }
  23.     std::cout << "Gray Code : " << gray << std::endl
  24.               << "Binary Code : " << binary << std::endl;
  25.     return 0;       
  26. }

$ a.out
Enter the gray code 1000
Gray Code : 1000
Binary Code : 1111
$ a.out
Enter the gray code 0101
Gray Code : 0101
Binary Code : 0110

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.