basics · intermediate · ~15 min

Binary to Gray code

Convert a binary value to reflected Gray code.

Challenge

Implement:

unsigned binary_to_gray(unsigned x);

Return the reflected Gray code of x, where consecutive values differ by exactly one bit.

Input format

x.

Output format

The Gray-coded value.

Constraints

None.

Starter code

#include <stddef.h>
/* Convert an unsigned binary value to its reflected Gray code. */
unsigned binary_to_gray(unsigned x){ return x; }

Common mistakes

Shifting left instead of right; forgetting it's XOR, not OR.

Edge cases to handle

0->0, 1->1, 2->3, 3->2 (each step flips one bit).

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.