Q:

C# program to convert a decimal number into a hexadecimal number

belongs to collection: C# Basic Programs | basics

0

C# program to convert a decimal number into a hexadecimal number

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program:

The source code to convert a decimal number into hexadecimal number is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to convert a decimal number into hexadecimal number.

using System;
using System.Globalization;

class ConvertDemo
{
    static void Main()
    {
        int decNum=0;
        
        int i   = 0;
        int rem = 0;

        string hexNum  = "";
        
        Console.Write("Enter a Decimal Number :");
        decNum = int.Parse(Console.ReadLine());
        
        while (decNum != 0)
        {
            rem = decNum % 16;
            if (rem < 10)
                rem = rem + 48;
            else
                rem = rem + 55;

            hexNum += Convert.ToChar(rem);
            decNum = decNum / 16;
        }

        Console.Write("Hexa-decimal number :");
        for (i = hexNum.Length - 1; i >= 0; i--)
            Console.Write(hexNum[i]);

        Console.WriteLine();
    }
}

Output:

Enter a Decimal Number :30
Hexa-decimal number :1E
Press any key to continue . . .

Explanation:

In the above program, we create a class ConvertDemo that contains the Main() method, In the Main() method we read a decimal number from the keyboard and then convert the decimal number into a corresponding hexadecimal number.

while (decNum != 0)
{
    rem = decNum % 16;
    if (rem < 10)
        rem = rem + 48;
    else
        rem = rem + 55;

    hexNum += Convert.ToChar(rem);
    decNum = decNum / 16;
}

In the above code, we find the remainder of the decimal number after dividing by 16 and then concatenated into the string that will contain a reversed hex number.

Console.Write("Hexa-decimal number :");
for (i = hexNum.Length - 1; i >= 0; i--)
    Console.Write(hexNum[i]);

In the above code, we print the string in reverse order that will print correct hex number on the console screen.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# Basic Programs | basics

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C# program to convert a hexadecimal number into a ... >>
<< C# program to convert a meter into kilo-meter and ...