A few days ago
bal3it

Generating gray code using C++??

Write a program in C++ to find the Gray code for a given number of bits n using the algorithm presented in class**. Your program should take as input the variable n (integer > 0) and give as output the Gray-encoded list of codewords in a neat and clean format.

**Here is the explanation in the lecture:

– Only 1 bit changes between each pair of consecutive codewords

– It is a reflective code

– For a 1 bit code –> 0 and 1

– For (N+1)-bit code, the first 2N are the same of N-bit code with a leading zero

– The last 2N codewords are the reverse of N-bit code with a leading 1

Here is the gray code for 3 bits:

000

001

011

010

110

111

101

100

I also wrote the gray codes of 5 bits to check the pattern and what’s happening (I didn’t reach to any conclusion)…

I need some help from any one of you. Just post ideas and explanations!

Top 2 Answers
A few days ago
vaibhav s

Favorite Answer

Let B[n:0] be the input array of bits in the usual binary representation, [0] being LSB

Let G[n:0] be the output array of bits in Gray code

G[n] = B[n]

for i = n-1 downto 0

G[i] = B[i+1] XOR B[i]

This algorithm can be rewritten in terms of words instead of arrays of bits:

G = B XOR (SHR(B))

For instance in C or java langages :

g = b ^ (b >> 1);

1

4 years ago
mcgray
Gray Code Generator
0