sunmoon - 5 months ago 45

C Question

Given a gray code for a number, find the binary code for the number.

Gray code is a binary numeral system where two successive values differ in only one bit.

For Example two bit gray code is:

0 - 00

1 - 01

2 - 11

3 - 10

Binary is:

0 - 00

1 - 01

2 - 10

3 - 11

Provide an algorithm to convert the gray code of the number to binary code.

For example, input is 11. Expected output is 10.

Answer

Converting the Gray code to binary is:

Retain the Most significant bit as it is and for the rest of the bits keep xoring the successive bits.

ie Gn Gn-1 Gn-2 ........ G1 is the gray code and Bn Bn-1 .......B1 is the binary code.

Bn= Gn and for all the other bits Bn-1 = Gn-1 XOR Gn