The Gray code is a fascinating contraption with a rich historical legacy, but still useful in a number of important applications.
I was interested in how difficult it is to implement idiomatic Erlang functions that convert to and from Gray code. It turned out to be surprisingly easy.
Converting a binary (represented as an ordinary nonnegative integer) to Gray code:
Converting a number in Gray code back to its corresponding ordinal:
Note that the implementations are not restricted to any number of bits. Since Erlang supports arbitrary precision arithmetics, the functions should work for as large numbers as constrained by available memory.
For any bit width B, the gray codes corresponding to 0..2B-1 will be cyclic. That is, the codes for 0 and 2B-1 will also differ in exactly one bit, just like any two adjacent codes.
To print a table of gray codes for a given bit width Bits:
For Bits = 4, we get this table:
Download complete module with all code.