basics · intermediate · ~15 min
Convert a binary value to reflected Gray code.
Implement:
unsigned binary_to_gray(unsigned x);
Return the reflected Gray code of x, where consecutive values differ by exactly one bit.
x.
The Gray-coded value.
None.
#include <stddef.h>
/* Convert an unsigned binary value to its reflected Gray code. */
unsigned binary_to_gray(unsigned x){ return x; }
Shifting left instead of right; forgetting it's XOR, not OR.
0->0, 1->1, 2->3, 3->2 (each step flips one bit).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.