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

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

Program:

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.






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.