Given an integer in hexadecimal format, we have to convert it into a decimal format in C#.
给定十六进制格式的整数,我们必须使用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:
要将十六进制值转换为十进制值,我们使用Convert.ToInt32()函数,方法是指定给定数字格式的基础,其语法为:
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).
variable_name是一个包含十六进制值的变量(我们也可以提供十六进制值)。
16 is the base of the hexadecimal value.
16是十六进制值的基数。
Example:
例:
Input:
hex_value = "10FA"
Output:
int_value = 4346
C# code to convert hexadecimal to decimal
C#代码将十六进制转换为十进制
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.
我们知道,十六进制值包含0到9 , A到F和a到f的数字 ,如果存在无效字符,则将不会进行转换并且会引发错误。
In the given example, there is an invalid character 'T' in the hex_value, thus, the program will throw an error.
在给定的示例中, hex_value中存在无效字符'T' ,因此程序将引发错误。
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)...
翻译自: https://www.includehelp.com/dot-net/convert-a-hexadecimal-value-to-decimal-in-c-sharp.aspx