Grey Code - Reflected Binary Code

Grey Code, also known as Reflected Binary Code (RBC), is an ordering of the binary numeral system such that two successive values differ in only one bit (binary digit). It was named after Frank Gray, who patented it for use in pulse code modulation in 1947.

Key Property: Unlike standard binary, moving from one number to the next in Grey Code involves flipping exactly one bit.

Why do we need Grey Code?

In standard binary, transitioning from 3 (011) to 4 (100) requires three bits to change simultaneously. In physical hardware, these switches might not happen at the exact same instant. A sensor might briefly read 111 or 110, leading to critical errors in systems like rotary encoders or high-speed digital communications.

Construction of N-bit Grey Code

The "Reflected" property comes from the method used to generate the sequence. To generate an n-bit Grey code from (n-1) bits:

  1. Start with the (n-1) bit code.
  2. Write the sequence in reverse order (reflection).
  3. Prefix 0 to the original sequence.
  4. Prefix 1 to the reflected sequence.

4-Bit Binary vs Grey Code Table

Decimal Binary Grey Code
000000000
100010001
200100011
300110010
401000110
501010111
601100101
701110100

Conversions

1. Binary to Grey Code

To convert a binary string B to Grey code G:

  • The MSB (Most Significant Bit) of the Grey code is the same as the MSB of the binary number.
  • The remaining bits are found by performing XOR between the current binary bit and the previous binary bit.

Logical Expression: G = B ^ (B >> 1)

2. Grey Code to Binary

To convert Grey code G back to binary B:

  • The MSB remains the same.
  • For subsequent bits: B[i] = B[i+1] ^ G[i].

Implementation in JavaScript

/**
 * Binary to Grey Code
 */
function binaryToGrey(n) {
    return n ^ (n >> 1);
}

/**
 * Grey Code to Binary
 */
function greyToBinary(n) {
    let binary = 0;
    for (; n > 0; n >>= 1) {
        binary ^= n;
    }
    return binary;
}

// Testing with Decimal 4
const greyValue = binaryToGrey(4); // Returns 6 (binary 110)
console.log("Grey Code:", greyValue.toString(2));
    

Applications

  • Karnaugh Maps: Used to simplify Boolean algebraic expressions.
  • Error Correction: Minimizes errors in digital-to-analog conversions.
  • FIFO Buffers: Used in asynchronous systems to pass pointers between clock domains.
  • Genetic Algorithms: Used to represent chromosomes where small changes are desired during mutation.