C# Program to Convert Decimal to Binary

In this article, find the C# Program to Convert Decimal to Binary.


C# Program to Convert Decimal to Binary:

Here is an example of a C# program that converts a decimal number to its binary representation:


using System;

class DecimalToBinary
{
    static void Main(string[] args)
    {
        int decimalNumber;
        int[] binaryNumber = new int[10];
        int i = 0;

        Console.Write("Enter a decimal number: ");
        decimalNumber = int.Parse(Console.ReadLine());

        while (decimalNumber > 0)
        {
            binaryNumber[i] = decimalNumber % 2;
            decimalNumber = decimalNumber / 2;
            i++;
        }

        Console.Write("Binary representation of the decimal number is: ");
        for (int j = i - 1; j >= 0; j--)
        {
            Console.Write(binaryNumber[j]);
        }
        Console.ReadLine();
    }
}

This program prompts the user to enter a decimal number, converts it to binary, and then displays the binary representation. The program uses a while loop to repeatedly divide the decimal number by 2 and store the remainder in an array. The array is then displayed in reverse order to show the binary representation of the decimal number.

Here is an another example of a C# program that can convert a decimal number to its binary representation:

using System;

class Program
{
    static void Main(string[] args)
    {
        int decimalNumber, remainder;
        string binary = "";

        Console.Write("Enter a decimal number: ");
        decimalNumber = int.Parse(Console.ReadLine());

        while (decimalNumber > 0)
        {
            remainder = decimalNumber % 2;
            decimalNumber = decimalNumber / 2;
            binary = remainder + binary;
        }

        Console.WriteLine("Binary: " + binary);
    }
}

This program uses the modulus operator (%) to determine the remainder of the decimal number when divided by 2. This remainder is then added to the binary string. The program then uses integer division (/) to divide the decimal number by 2, and the process is repeated until the decimal number is equal to 0. The final binary string is then displayed as the output.

You can also use .ToString(“X”) method to convert decimal to hexadecimal. The letter X is the format specifier for hexadecimal.


– Article ends here –

If you have any questions, please feel free to share your questions or comments on the comment box below.

Share this:
We will be happy to hear your thoughts

      Leave a reply

      www.troubleshootyourself.com
      Logo