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

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

Hexadecimal to Decimal Conversion in C#

Here we will read a hexadecimal number then convert the entered number into a decimal number using int.Parse() method.

C# program for hexadecimal to decimal conversion

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

//C# program to convert a hexadecimal number into a decimal number.
using System;
using System.Globalization;

class ConvertDemo
{
    static int hex2dec(string hexNum)
    {
        int decNum = 0;

        decNum = int.Parse(hexNum, NumberStyles.HexNumber);

        return decNum;
    }
    static void Main()
    {
        string hexNum = "";
        int decNum    = 0;

        Console.Write("Enter a hexa-decimal number: ");
        hexNum = Console.ReadLine();

        decNum = hex2dec(hexNum);
        
        Console.WriteLine("Decimal number: " + decNum);
    }
}

Output

Enter a hexa-decimal number: 1F
Decimal number: 31
Press any key to continue . . .

Explanation

In the above program, we created a class ConvertDemo that contains two static methods hex2dec() and Main(). The hex2dec() method is used to convert a hexadecimal number into a decimal number using Parse() method of int structure. In the Main() method, we read the hexadecimal number and pass to the hex2dec() method that returns the converted decimal number then we printed the result on the console screen.

C# Basic Programs »


Related Programs




Comments and Discussions!

Load comments ↻






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