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.
/*
* C++ Program to Convert Gray Code to Binary Code
*/
#include <iostream>
#include <string>
int main(int argc, char* argv[])
{
std::string gray, binary;
std::cout << "Enter the gray code ";
std::cin >> gray;
binary = gray[0];
for (int i = 0; i < gray.length() - 1; i++)
{
/* XOR operation */
if (binary[i] == gray[i+1])
binary = binary + "0";
else
binary = binary + "1";
}
std::cout << "Gray Code : " << gray << std::endl
<< "Binary Code : " << binary << std::endl;
return 0;
}
$ 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.
Related Posts:
- Apply for Computer Science Internship
- Apply for C++ Internship
- Practice Computer Science MCQs
- Check Programming Books
- Check C++ Books