The reflected binary code or Gray code is an ordering of the binary numeral system such that two successive values differ in only one bit (binary digit). Gray codes are very useful in the normal sequence of binary numbers generated by the hardware that may cause an error or ambiguity during the transition from one number to the next. So, the Gray code can eliminate this problem easily since only one bit changes its value during any transition between two numbers.
Gray code is not weighted that means it does not depends on positional value of digit. This cyclic variable code that means every transition from one value to the next value involves only one bit change.
Gray code also known as reflected binary code, because the first (n/2) values compare with those of the last (n/2) values, but in reverse order.
n-bit Gray code can be generated recursively using reflect and prefix method which is explained as following below.
Therefore, Gray code 0 and 1 are for Binary number 0 and 1 respectively. Gray codes: 00. 01, 11, and 10 are for Binary numbers: 00, 01, 10, and 11 respectively. Similarly you can construct Gray code for 3 bit binary numbers:
Therefore, Gray codes are as following below,
For n = 1 bit | For n = 2 bit | For n = 3 bit | |||
---|---|---|---|---|---|
Binary | Gray | Binary | Gray | Binary | Gray |
0 | 0 | 00 | 00 | 000 | 000 |
1 | 1 | 01 | 01 | 001 | 001 |
| 10 | 11 | 010 | 011 | |
11 | 10 | 011 | 010 | ||
| 100 | 110 | |||
101 | 111 | ||||
110 | 101 | ||||
111 | 100 |
Iterative method of generating G(n+1) from Gn are given below. This is simpler method to contract Gray code of n-bit Binary numbers. Each bit is inverted if the next higher bit of the input value is set to one. The nth Gray code is obtained by computing n⊕(floor(n/2)).
The hamming distance of two neighbours Gray codes is always 1 and also first Gray code and last Gray code also has Hamming distance is always 1, so it is also called Cyclic codes.
You can construct Gray codes using other methods but they may not be performed in parallel like given above method. For example, 3 bit Gray codes can be contracted using K-map which is given as following below:
Decimal | Binary | Gray Code |
---|---|---|
0 | 000 | 000 |
1 | 001 | 001 |
2 | 010 | 011 |
3 | 011 | 010 |
4 | 100 | 110 |
5 | 101 | 111 |
6 | 110 | 101 |
7 | 111 | 100 |
There are also other types of Gray codes, like Beckett-Gray code, Single track Gray codes etc.
Gray codes are used in rotary and optical encoders, Karnaugh maps, and error detection.