Saturday 2 December 2017

C# Program to Create a Gray Code


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();
    }
}


Output:

Number Gray
0            0
1            1
2            11
3            10
4            110
5            111
6            101
7            100
8            1100
9            1101


More C# Programs:
















100+ Best Home Decoration Ideas For Christmas Day 2019 To Make Home Beautiful

Best gifts for Christmas Day | Greeting cards for Christmas Day | Gift your children a new gift on Christmas day This Christmas d...