Last week I was coding up some Genetic Algorithm programs. In the past I’ve used mostly C/C++ but this time I wanted to use C#. The first step when implementing GAs is to get your Gray Code routines ready. GAs typically encode information using Gray Code rather than ordinary binary representations. I figured there’d be several sets of C# implementations of Gray Code routines available on the Internet, but a couple hour search yielded only some very weak (and often completely incorrect) sets of code. So, I wrote my own micro-library. One of the big problems is defining exactly what is meant by a Gray Code library. There are many, many variations. Additionally, there is the annoying but not trivial issue of internal representation (where the low-order / least significant bit is stored, and the readable representation (left to right or right to left). In my case, I needed to work with normal C# int types in the range of 0-255 (such as 15), ordinary binary representations of these ints (such as 1111 — 15 in binary — in standard readable form), and Gray Code representations (such as 1000 — 15 in Gray code). In my case I decided to store binary and Gray codes in memory as arrays of 0 and 1 ints. I came up with six convert routines: int to binary, binary to Gray, int to Gray, binary to int, Gray to binary, and Gray to int. For example,

int n = 15;

int[] binary = IntToBinary(n); // binary holds [1 1 1 1]

int[] gray = IntToGray(n); // gray holds [0 1 1 1]

int[] binary = IntToBinary(n); // binary holds [1 1 1 1]

int[] gray = IntToGray(n); // gray holds [0 1 1 1]

or

int[] gray = new int[] { 0, 1, 0, 1 };

int n = GrayToInt(gray); // n holds 12

int n = GrayToInt(gray); // n holds 12

I’ll post the code in my next blog entry. The moral of the story is that if you are going to work with Gray Code using C#, be prepared to have to spend a couple of hours defining your own custom conversion library.