This C# Program Creates a Gray Code. A Gray code is an encoding of numbers so that adjacent numbers have a single digit differing by 1. The term Gray code is often used to refer to a “reflected” code, or more specifically still, the binary reflected Gray code.
Here is source code of the C# Program to Create a Gray Code. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.
/*
* C# Program to Create a Gray Code
*/
using System;
public class Gray
{
public static ulong grayEncode(ulong n)
{
return n ^ (n >> 1);
}
public static ulong grayDecode(ulong n)
{
ulong i = 1 << 8 * 64 - 2; //long is 64-bit
ulong p, b = p = n & i;
while ((i >>= 1) > 0)
b |= p = n & i ^ p >> 1;
return b;
}
public static void Main(string[] args)
{
Console.WriteLine("Number\tGray");
for (ulong i = 0; i < 10; i++)
{
Console.WriteLine(string.Format("{0}\t{1}", i, Convert.ToString((long)grayEncode(i), 2)));
}
Console.Read();
}
}
Here is the output of the C# Program:
Number Gray 0 0 1 1 2 11 3 10 4 110 5 111 6 101 7 100 8 1100 9 1101
Sanfoundry Global Education & Learning Series – 1000 C# Programs.
If you wish to look at all C# Programming examples, go to 1000 C# Programs.