A Gray Code Mini-Library in C#

In my last blog entry I described how I recently needed a set of Gray Code conversion routines in the C# language. Here is the mini-library I wrote. First, my library assumes an 8-bit system, which can represent unsigned integers in the range 0 to 255. Second, the bit representation of an integer is an 8-cell int array, where each array holds 0 or 1. Third, the bit representation stores the least significant bit at array index [0], and the most significant bit at array index [7].
 
static int[] IntToBinary(int n)
{
  int[] binary = new int[8];
  int i = 0;
  do {
    binary[i++] = n % 2;
  } while ((n /= 2) > 0);
  return binary;
}
 
static int BinaryToInt(int[] binary)
{
  int ans = 0;
  for (int i = 0; i <=7; ++i) {
    ans = ans + (int)Math.Pow(2, i) * binary[i];
  }
      return ans;
}
 
static int[] BinaryToGray(int[] binary)
{
  int[] gray = new int[8];
  gray[7] = binary[7]; // copy high-order bit
  for (int i = 6; i >= 0; –i) { // remaining bits
    if (binary[i] == 0 && binary[i + 1] == 0)
      gray[i] = 0;
    else if (binary[i] == 1 && binary[i + 1] == 1)
      gray[i] = 0;
    else if (binary[i] == 0 && binary[i + 1] == 1)
      gray[i] = 1;
    else if (binary[i] == 1 && binary[i + 1] == 0)
      gray[i] = 1;
  }
  return gray;
}
 
static int[] GrayToBinary(int[] gray)
{
  int[] binary = new int[8];
  binary[7] = gray[7]; // copy high-order bit
  for (int i = 6; i >= 0; –i) { // remaining bits
    if (gray[i] == 0 && binary[i + 1] == 0)
      binary[i] = 0;
    else if (gray[i] == 1 && binary[i + 1] == 1)
      binary[i] = 0;
    else if (gray[i] == 0 && binary[i + 1] == 1)
      binary[i] = 1;
    else if (gray[i] == 1 && binary[i + 1] == 0)
      binary[i] = 1;
  }
  return binary;
}
 
static int[] IntToGray(int n)
{
  int[] binary = IntToBinary(n);
  int[] gray = BinaryToGray(binary);
  return gray;
}
 
static int GrayToInt(int[] gray)
{
  int[] binary = GrayToBinary(gray);
  int n = BinaryToInt(binary);
  return n;
}
 
static void showBitsInMemory(int[] bits)
{
  Console.Write("[");
  for (int i = 0; i < bits.Length; ++i) {
    Console.Write(bits[i] + " ");
  }
  Console.WriteLine("]");
}
 
static void showBitsStandard(int[] bits) 
{
  Console.Write("[ ");
  for (int i = bits.Length – 1; i >= 0; –i) {
    Console.Write(bits[i] + " ");
  }
  Console.WriteLine("]");
}
 
 
   
Advertisements
This entry was posted in Machine Learning, Software Test Automation. Bookmark the permalink.