top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to convert gray code to binary and binary to gray using C/C++?

0 votes
2,747 views
How to convert gray code to binary and binary to gray using C/C++?
posted Feb 18, 2016 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

gray code to binary

/*
 * 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;       
}

Output:

$ 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

binary to gray

/*
 * C Program to Convert Binary Code of a Number into its Equivalent 
 * Gray's Code without using Recursion
 */
#include <stdio.h>
#include <math.h>

int bintogray(int);

int main ()
{
    int bin, gray;

    printf("Enter a binary number: ");
    scanf("%d", &bin);
    gray = bintogray(bin);
    printf("The gray code of %d is %d\n", bin, gray);
    return 0;
}

int bintogray(int bin)
{
    int a, b, result = 0, i = 0;

    while (bin != 0)
    {
        a = bin % 10;
        bin = bin / 10;
        b = bin % 10;
        if ((a && !b) || (!a && b))
        {
            result = result + pow(10, i);
        }
        i++;
    }
    return result;
}

Output:

$ cc pgm26.c -lm
$ a.out
Enter a binary number: **********
The gray code of ********** is **********
answer Feb 19, 2016 by Shivaranjini
...