2013-12-18 28 views
0

当我编译和运行下面的代码,它引发以下例外:为什么在十进制和十六进制之间进行转换会抛出一个formatexception?

未处理的异常信息:System.FormatException:指定的格式“X”是在System.NumberFormatter.NumberToString无效 (System.String格式System.Decimal.ToString(System.String,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格式,IFormatProvider提供程序)[0x00000]中: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”)。

+1

另一个问题使用术语十进制作为一个基地10号。它使用'int'类型的格式化值而不是'decimal'。 – Anthony

+1

在他们使用int变量的例子中。我认为你将十进制数据类型与将十进制(整数)转换为十六进制时使用的通用术语相混淆。 –

回答

6

基于MSDN article的X格式类型,只能使用Integral类型。

结果:十六进制字符串。 受支持:仅限Integral类型。 精度说明符:结果字符串中的位数。更多 信息:HexaDecimal(“X”)格式说明符。

所以你需要指定INT,而不是小数。由于十六进制格式仅存在于整数值中。

+1

有道理。非常感谢! – Mansfield

1

你的代码更改为:

int result = 1454787509433225637; 
相关问题