4 ways in C# to convert a hexadecimal value to Decimal

C# program to convert a hexadecimal value to Decimal:

In this post, we will learn how to convert a hexadecimal value to decimal in C#. The program will take the hexadecimal value as an input from the user and print the decimal conversion. The hexadecimal value is stored as a string and the decimal value as an integer.

Hexadecimal and Decimal number system:

The hexadecimal number system is a base-16 number system. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, and F are used to represent a number in the hexadecimal number system. Lowercase characters are also used i.e. a, b, c, d, e, and f.

Similarly, the decimal number system is a base-10 number system. 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9 are the numerals or digits used to represent a number in the decimal number system.

How to convert a Hexadecimal number to Decimal:

We can follow the following algorithm to convert a hexadecimal number to decimal.

  • Start from the rightmost digit of the hexadecimal number.
  • Multiply it with 16^n, where n starts from 0.
  • Add the multiplication to a final variable.
  • Always take the decimal equivalent for the hexadecimal digit, e.g. for A or a, take it as 10, for B or b, take it as 11, etc.

Method 1: C# program to convert a Hexadecimal number to Decimal without using an inbuilt method:

The below program uses the above algorithm to convert a hexadecimal number to decimal. It finds the final decimal value by iterating through the characters of the hexadecimal number.

using System;

namespace Program
{
    class Program
    {
        static int HexaToDecimal(char c)
        {
            switch (c)
            {
                case '0':
                    return 0;
                case '1':
                    return 1;
                case '2':
                    return 2;
                case '3':
                    return 3;
                case '4':
                    return 4;
                case '5':
                    return 5;
                case '6':
                    return 6;
                case '7':
                    return 7;
                case '8':
                    return 8;
                case '9':
                    return 9;
                case 'A':
                case 'a':
                    return 10;
                case 'B':
                case 'b':
                    return 11;
                case 'C':
                case 'c':
                    return 12;
                case 'D':
                case 'd':
                    return 13;
                case 'E':
                case 'e':
                    return 14;
                case 'F':
                case 'f':
                    return 15;
            }
            return -1;
        }

        static int HexaToDecimal(string HexaDecimalString)
        {
            int Decimal = 0;
            int Multiplier = 1;

            for (int i = HexaDecimalString.Length - 1; i >= 0; i--)
            {
                Decimal += HexaToDecimal(HexaDecimalString[i]) * Multiplier;
                Multiplier *= 16;
            }
            return Decimal;
        }
        static void Main(string[] args)
        {
            string HexaDecimal;

            Console.WriteLine("Enter the hexadecimal number: ");
            HexaDecimal = Console.ReadLine();

            Console.WriteLine("Decimal: " + HexaToDecimal(HexaDecimal));
        }
    }
}

Here,

  • It is reading the hexadecimal number as an input from the user. This value is stored in the string variable HexaDecimal.
  • The HexaToDecimal method is used to convert a hexadecimal string or character to decimal. We have two overloading methods. The Main method is calling the one that takes a string as the parameter.
  • In HexaToDecimal:
    • Decimal is an integer variable to hold the final decimal value. Multiplier is another integer value. It is the value of 16^n. It is initialized as 16^0 or 1.
    • The for loop iterates through the hexadecimal string from the last character to the first.
    • On each iteration, we are calling HexaToDecimal method to get the decimal value for that specific character. This value is multiplied with Multiplier and adds it to Decimal to calculate the final decimal value.
    • The value of Multipler is updated by multiplying it by 16.
    • At the end of this method, it returns the Decimal value.

If you run this program, it will print output as like below:

Enter the hexadecimal number: 
11dA
Decimal: 4570

Method 2: By using Convert.ToInt32():

The ToInt32 method makes it easy to do hexadecimal to decimal conversion. This method can take a string value and the base as its parameters and returns the converted integer value. It is defined as like below:

public static int ToInt32 (string? value, int base);

This is a static method defined in the Convert class. This method takes the hexadecimal value as a string as the first parameter and base as the second parameter. Since we are converting a hexadecimal value to decimal, we have to pass 16 as base. It returns an integer value.

using System;

namespace Program
{
    class Program
    {
        static void Main(string[] args)
        {
            string HexaDecimal;

            Console.WriteLine("Enter the hexadecimal number: ");
            HexaDecimal = Console.ReadLine();

            Console.WriteLine("Decimal: " + Convert.ToInt32(HexaDecimal, 16));
        }
    }
}

If you run this program, it will print similar output:

Enter the hexadecimal number: 
11da
Decimal: 4570

Enter the hexadecimal number: 
12ae8
Decimal: 76520

For invalid values, it will throw an FormatException.

Enter the hexadecimal number: 
yt87
Unhandled exception. System.FormatException: Could not find any recognizable digits.
   at System.ParseNumbers.StringToInt(ReadOnlySpan`1 s, Int32 radix, Int32 flags, Int32& currPos)
   at System.Convert.ToInt32(String value, Int32 fromBase)
   at Program.Program.Main(String[] args) in /c-sharp/Program/Program.cs:line 14

You can use a try-catch block to handle these type of exceptions.

using System;

namespace Program
{
    class Program
    {
        static void Main(string[] args)
        {
            string HexaDecimal;

            Console.WriteLine("Enter the hexadecimal number: ");
            HexaDecimal = Console.ReadLine();

            try
            {
                Console.WriteLine("Decimal: " + Convert.ToInt32(HexaDecimal, 16));
            }
            catch (FormatException)
            {
                Console.WriteLine("Unable to parse");
            }
        }
    }
}

Method 3: By using int.Parse:

The int.Parse method is used to parse a string to number in C#. We can use this method to convert a hexadecimal value to integer.

We will use the following overload:

public static Int32 Parse(string s, NumberStyles style)

It takes the string as the first parameter and a NumberStyles as the second parameter. We will provide NumberStyles.HexNumber to parse a hexadecimal string. It returns an integer value.

using System;

namespace Program
{
    class Program
    {
        static void Main(string[] args)
        {
            string HexaDecimal;

            Console.WriteLine("Enter the hexadecimal number: ");
            HexaDecimal = Console.ReadLine();

            try
            {
                Console.WriteLine("Decimal: " + int.Parse(HexaDecimal, System.Globalization.NumberStyles.HexNumber));
            }
            catch (FormatException)
            {
                Console.WriteLine("Unable to parse");
            }
        }
    }
}

We have to use a try-catch block because it also throws FormatException.

It will give similar output.

Method 4: With int.TryParse:

int.TryParse method is another way to parse a hexadecimal value to decimal. We don’t have to use a try-catch block with this method. This method returns a boolean value and based on it, we can print the result.

Below is the complete program:

using System;

namespace Program
{
    class Program
    {
        static void Main(string[] args)
        {
            string HexaDecimal;

            Console.WriteLine("Enter the hexadecimal number: ");
            HexaDecimal = Console.ReadLine();

            if (int.TryParse(HexaDecimal, System.Globalization.NumberStyles.HexNumber, null, out int Result))
            {
                Console.WriteLine("Decimal: " + Result);
            }
            else
            {
                Console.WriteLine("Unable to parse");
            }
        }
    }
}

It will give similar results. C# hexadecimal to decimal

You might also like: