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#?
Submitted by Nidhi, on September 14, 2020

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

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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.