Binary to Gray Code Conversion C Program in C++ (Easy Explanation)

Binary to Gray code conversion is a very common topic in Computer Science world especially for students learning C/C++, digital logic and data representation. Many students understand binary numbers but feel confused when Gray code comes in exams or practicals.

In this article you will learn binary to gray code conversion using C++, explained in very simple language, so even beginners can understand it easily.

What is Gray Code?

Gray code is a binary number system where only one bit changes at a time when moving from one number to the next. This help to the reduces errors in digital systems.

Example:

  • Binary: 1011
  • Gray Code: 1110

Binary to Gray Code Logic

The most commonly used formula is:

Gray = Binary XOR (Binary >> 1)

  • First bit remains same
  • Every next bit is XOR of current and previous bit

C++ Program: Binary to Gray Code Conversion

				
					#include <iostream>
using namespace std;

int main() {
    int binary, gray;

    cout << "Enter a binary number: ";
    cin >> binary;

    gray = binary ^ (binary >> 1);

    cout << "Gray code is: " << gray;

    return 0;
}

				
			

How the Program Works

  • User enters a binary number
  • The number is right-shifted by one bit
  • XOR operation is applied
  • Gray code is generated and printed

This program is perfect for exams, viva and also the  practice.

Applications of Gray Code

  • Digital encoders
  • Error reduction circuits
  • Karnaugh maps
  • Communication systems

Recommended : Binary to Gray Code Converter – Step-by-Step Example

Why is Gray code used instead of binary?

Because Gray code reduces errors by changing only one bit at a time.

Is this C++ program exam friendly?


Yes, it is simple, logical, and commonly accepted in exams.

Can this logic be used in other languages?


Yes the same XOR logic works in Python, Java, and C.

Leave a Reply

Your email address will not be published. Required fields are marked *