C# Program to Create a Gray Code
Posted by Superadmin on August 13 2022 08:10:08

C# Program to Create a Gray Code

 

This is a C# Program to create a gray code.

Problem Description

This C# Program Creates a Gray Code.

Problem Solution

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.

Program/Source 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();
    }
}
Program Explanation

In this C# program, using for loop we are entering the number of elements. The grayEncode() function is used to convert the number into 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.

 

In grayDecode() function compute the Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. Multiply the resulted value with 64. Compute the difference between the resulted values by 2.

Using while loop compute the Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. Check the resulted value is greater than 0, if the condition is true then execute the statement and compute the Binary Right Shift Operator.

The left operands value 1 is moved right by the number of bits specified by the right operand value of ‘p’ variable, Using Binary AND Operator copy a bit to the result if it exists in both operands. Convert the resulted value to Binary OR Operator. Copy a bit if it exists in either operand to ‘b’ variable. Print the gray code of the number.

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