Simvik

Decode a Gray code

Convert a reflected Gray code back to binary. A medium embedded C problem (Bit manipulation), run and graded in the browser.

medium · Bit manipulation · encoders · xor

Rotary encoders report position in Gray code so that only one bit changes per step. A binary value n is encoded as n ^ (n >> 1).

Given a Gray-coded value g, return the original binary value.

Starter code

uint32_t gray_to_binary(uint32_t g) {
  // Encoding is g = n ^ (n >> 1). Undo it.
  return g;
}

Example tests

Gray 110

printf("%u\n", gray_to_binary(6));

Expected output:

4

Gray 111

printf("%u\n", gray_to_binary(7));

Expected output:

5

Learn it first

  • Bit manipulation · Masks, shifts, fields and the idioms every register access is built from.

More Bit manipulation problems