# Convert Binary code to Gray code in C++

Gray code is a binary number system in which each successive value can only differ by one bit. In this tutorial, we will learn how to convert binary code to gray code in C++.

## How to convert the binary code to gray code in C++

To convert the binary code to gray code, there is a simple process. i.e. to convert the binary code to gray first copy the leftmost significant bit, that will be the first bit of gray code. for remaining bits of gray code. find the XOR operation of leftmost and second leftmost significant bit. and place it as the next element of gray code. change the leftmost and second left most significant and do the same for next bit in the gray code.

Let’s take an example to understand it in a better way.

Example:

```consider a 6 bit binary code 110110

- first bit form left side of gray code will be the first bit from left side of
binary code i.e 1.
- for second bit of gray code, find XOR operation on first and second bit of
binary code i.e. 1 XOR 1 = 0
- For third bit of gray code, find XOR operation on second and third bit of
binary code i.e. 1 XOR 0 = 1
- For forth bit of gray code, find XOR operation on third and forth bit of
binary code i.e. 0 XOR 1 = 1
- For fifth bit of gray code, find XOR operation on forth and fifth bit of
binary code i.e. 1 XOR 1 = 0
- For sixth bit of gray code, find XOR operation on fifth and sizth bit of
binary code i.e. 1 XOR 0 = 1

Therefore, the gray code of given binary code is 101101```

### Algorithm

1. Initialize or input the binary code form the output.
2. declare a variable gray and i, and initialize them with 0.
3. start loop till the binary number is not equal to zero.
a) extract the last and second last element form binary code and save it to two variables, consider a and b.
b) If XOR of and is not equal to zero then add 10^i to present value of gray.
c) increment i with 1.
4. display gray.

## C++ program to convert Binary Code to Gray Code

```#include <iostream>
#include <math.h>
using namespace std;

int main (){

long long  binary, a, b, i = 0, gray =0;

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

while (binary != 0)
{
a = binary % 10;      //taking last element in a
binary = binary / 10; //removing last element
b = binary % 10;      //taking second last element in b

if ((a && !b) || (!a && b)) //if XOR of a and b is not equal to zero
gray = gray + pow(10, i);

i++;
}

//printing gray code
cout << "Gray code: "<< gray;

return 0;
}
```

Output:

```Enter a binary number : 110110
Gray code: 101101```

You may also read:

### One response to “Convert Binary code to Gray code in C++”

1. BrownOctopus says:

really? all that code?
isn’t all that that the same as value ^= value >> 1;?