为什么在十进制和十六进制之间转换会引发格式异常? [英] Why does converting between decimal and hex throw a formatexception?

查看:21
本文介绍了为什么在十进制和十六进制之间转换会引发格式异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我编译并运行下面的代码时,它抛出以下异常:

When I compile and run the below code, it throws the following exception:

未处理的异常:System.FormatException:指定的格式X"无效在 System.NumberFormatter.NumberToString(System.String 格式,System.Globalization.NumberFormatInfo nfi)[0x00000] 中:0在 System.NumberFormatter.NumberToString(System.String 格式,十进制值,IFormatProvider fp)[0x00000] 中:0在 System.Decimal.ToString(System.String 格式,IFormatProvider 提供程序)[0x00000] 中:0在 System.Decimal.ToString(System.String 格式)[0x00000] 中:0在 Program.Main()

Unhandled Exception: System.FormatException: The specified format 'X' is invalid at System.NumberFormatter.NumberToString (System.String format, System.Globalization.NumberFormatInfo nfi) [0x00000] in :0 at System.NumberFormatter.NumberToString (System.String format, Decimal value, IFormatProvider fp) [0x00000] in :0 at System.Decimal.ToString (System.String format, IFormatProvider provider) [0x00000] in :0 at System.Decimal.ToString (System.String format) [0x00000] in :0 at Program.Main ()

using System;

class Program
{
    static void Main()
    {
        decimal result = 1454787509433225637;

                    //both these lines throw a formatexception
        Console.WriteLine(result.ToString("X"));
                    Console.WriteLine(string.Format("{0:x}", result));
    }
}

为什么会这样?根据 https://stackoverflow.com/a/74223/1324019 这应该编译正常(并输出14307188337151A5").

Why does this happen? According to https://stackoverflow.com/a/74223/1324019 this should compile fine (and output "14307188337151A5").

推荐答案

基于 MSDN 文章 对于 X 格式类型,您只能使用 Integral 类型.

Based on MSDN article for X format type you can use only Integral types only.

结果:一个十六进制字符串.支持:仅积分类型.精度说明符:结果字符串中的位数.更多的信息:十六进制(X")格式说明符.

Result: A hexadecimal string. Supported by: Integral types only. Precision specifier: Number of digits in the result string. More information: The HexaDecimal ("X") Format Specifier.

因此您需要指定 int 而不是 decimal.因为十六进制格式只存在于整数值.

So you need to specify int instead of decimal. Because Hex format exists only for integral values.

这篇关于为什么在十进制和十六进制之间转换会引发格式异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆