PROGRAM TO CONVERT BINARY CODE TO GRAY CODE
In this example, you will learn a program to convert the Binary code into its equivalent Gray code.
(To understand this program , you should have prior knowledge about binary codes , gray codes and its conversion algorithms. )
Here are some examples of binary and its equivalent gray code:
//Program to Convert Binary Code to Gray Code
#include<stdio.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;
if (!bin)
{
return 0;
}
else
{
a = bin % 10;
bin = bin / 10;
b = bin % 10;
if ((a && !b) || (!a && b))
{
return (1 + 10 * bintogray(bin));
}
else
{
return (10 * bintogray(bin));
}
}
}
#include<stdio.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;
if (!bin)
{
return 0;
}
else
{
a = bin % 10;
bin = bin / 10;
b = bin % 10;
if ((a && !b) || (!a && b))
{
return (1 + 10 * bintogray(bin));
}
else
{
return (10 * bintogray(bin));
}
}
}
Output:
Enter a binary number: 1011101
The gray code of 1011101 is 1110011.
So that's it ! Just try this code by your own. If you have any doubts then feel free to drop a comment . I'll be happy to answer your questions .
Keep coding....
Comments
Post a Comment