C# program to change over a hexadecimal value to decimal: Here, we will figure out how to change over a given hex value to the decimal value?
Given an integer in the hexadecimal arrangement, we need to change over it into a decimal organization in C#.
To change over a hexadecimal value to the decimal value, we use Convert.ToInt32() work by determining the base on given number organization, its syntax is:
integer_value = Convert.ToInt32(variable_name, 16);
Here,
- variable_name is a variable that contains the hexadecimal value (we can likewise give the hex value).
- 16 is the base of the hexadecimal value.
Example:
Input:
hex_value = "10FA"
Output:
int_value = 4346
C# code to change over 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 realize that a hex value contains digits from 0 to 9, A to F and a to f, if there is an invalid character, the change won’t happen and a mistake will be tossed.
In the given example, there is an invalid character ‘T‘ in the hex_value, in this way, the program will toss a blunder.
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:\JustTechReview
at System.Convert.ToInt32(String value, Int32 fromBase)...