Home »
C programs »
C number system conversion programs
C program to convert a Binary number to Gray Code
Here, we are going to learn how to convert a Binary number to Gray Code in C programming language?
Submitted by Nidhi, on July 09, 2021
Problem statement
Here, we will read a number in binary format (1's and 0's) from the user and then convert it into corresponding Gray Code.
C program to convert a Binary number to Gray Code
The source code to convert binary numbers to Gray code without using recursion is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.
// C program to convert binary number to Gray Code
#include <stdio.h>
#include <math.h>
int main()
{
unsigned long long int binNum = 0;
unsigned long long int gray = 0;
int a = 0;
int b = 0;
int i = 0;
printf("Enter a binary number: ");
scanf("%llu", &binNum);
while (binNum != 0) {
a = binNum % 10;
binNum = binNum / 10;
b = binNum % 10;
if ((a && !b) || (!a && b)) {
gray = gray + pow(10, i);
}
i++;
}
printf("The gray code: %llu", gray);
return 0;
}
Output
RUN 1:
Enter a binary number: 111111111100
The gray code: 100000000010
RUN 2:
Enter a binary number: 1100110011
The gray code: 1010101010
RUN 3:
Enter a binary number: 1111
The gray code: 1000
RUN 4:
Enter a binary number: 1010
The gray code: 1111
Explanation
In the above program, we created a main() function. The main() function is the entry point for the program. And, we read a number in binary format (1's and 0's) from the user and convert the input number from the corresponding gray code and printed the result on the console screen.
C Number System Conversion Programs »