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

Here, we are going to learn how to convert a decimal number into a hexadecimal number in C#? By Nidhi Last updated : April 15, 2023

Decimal to Hexadecimal Conversion in C#

Here we will read a decimal number then convert the entered number into hexadecimal.

C# program for decimal to hexadecimal conversion

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.

C# Basic Programs »


Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.