Home » C#.Net

Convert a hexadecimal value to decimal in C#

C# program to convert a hexadecimal value to decimal: Here, we are going to learn how to convert a given hex value to the decimal value?
Submitted by IncludeHelp, on February 26, 2019

Given an integer in hexadecimal format, we have to convert it into a decimal format in C#.

To convert a hexadecimal value to the decimal value, we use Convert.ToInt32() function by specifying the base on given number format, its syntax is:

    integer_value = Convert.ToInt32(variable_name, 16);

Here,

  • variable_name is a variable that contains the hexadecimal value (we can also provide the hex value).
  • 16 is the base of the hexadecimal value.

Example:

    Input:
    hex_value = "10FA"
    
    Output:
    int_value = 4346

C# code to convert hexadecimal to decimal

using System;
using System.Text;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            //declaring a variable and assigning hex value
            string hex_value = "10FA";

            //converting hex to integer
            int int_value = Convert.ToInt32(hex_value, 16);

            //printing the values
            Console.WriteLine("hex_value = {0}", hex_value);
            Console.WriteLine("int_value = {0}", int_value);

            //hit ENTER to exit
            Console.ReadLine();
        }
    }
}

Output

hex_value = 10FA
int_value = 4346

Testing with invalid hexadecimal value

As we know that a hex value contains digits from 0 to 9, A to F and a to f, if there is an invalid character, the conversion will not take place and an error will be thrown.

In the given example, there is an invalid character 'T' in the hex_value, thus, the program will throw an error.

using System;
using System.Text;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                //declaring a variable and assigning hex value
                string hex_value = "10FAT";

                //converting hex to integer
                int int_value = Convert.ToInt32(hex_value, 16);

                //printing the values
                Console.WriteLine("hex_value = {0}", hex_value);
                Console.WriteLine("int_value = {0}", int_value);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            //hit ENTER to exit
            Console.ReadLine();
        }
    }
}

Output

System.FormatException: Additional non-parsable characters are 
at the end of the string. at 
System.ParseNumbers.StringToInt(String s, Int32 radix, Int32 flags, 
Int32* currPos)
   at Test.Program.Main(String[] args) in F:\IncludeHelp
   at System.Convert.ToInt32(String value, Int32 fromBase)...


Comments and Discussions!

Load comments ↻





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