在C#中将十六进制值转换为十进制

给定十六进制格式的整数,我们必须使用C#将其转换为十进制格式。

要将十六进制值转换为十进制值,我们使用Convert.ToInt32()函数,方法是指定给定数字格式的基础,其语法为:

    integer_value = Convert.ToInt32(variable_name, 16);

这里,

  • variable_name是一个包含十六进制值的变量(我们也可以提供十六进制值)。

  • 16是十六进制值的基数。

示例

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

C#代码将十六进制转换为十进制

using System;
using System.Text;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            //声明变量并分配十六进制值
            string hex_value = "10FA";

            //将十六进制转换为整数
            int int_value = Convert.ToInt32(hex_value, 16);

            //打印值
            Console.WriteLine("hex_value = {0}", hex_value);
            Console.WriteLine("int_value = {0}", int_value);

            //按ENTER退出
            Console.ReadLine();
        }
    }
}

输出结果

hex_value = 10FA
int_value = 4346

使用无效的十六进制值进行测试

我们知道,十六进制值包含0到9,A到F和a到f的数字,如果存在无效字符,则不会进行转换并且会引发错误。

在给定的示例中,hex_value中存在无效字符'T',因此程序将引发错误。

using System;
using System.Text;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                //声明变量并分配十六进制值
                string hex_value = "10FAT";

                //将十六进制转换为整数
                int int_value = Convert.ToInt32(hex_value, 16);

                //打印值
                Console.WriteLine("hex_value = {0}", hex_value);
                Console.WriteLine("int_value = {0}", int_value);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            //按ENTER退出
            Console.ReadLine();
        }
    }
}

输出结果

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:\nhooo
   at System.Convert.ToInt32(String value, Int32 fromBase)...