为什么在十进制和十六进制之间转换会引发formatexception? [英] Why does converting between decimal and hex throw a formatexception?
问题描述
当我编译并运行以下代码时,它将引发以下异常:
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").
推荐答案
Based on MSDN article for X format type you can use only Integral types only.
结果:十六进制字符串.支持者:仅限整数类型.精度说明符:结果字符串中的位数.更多的信息:HexaDecimal("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 而不是十进制.因为十六进制格式仅适用于整数值.
So you need to specify int instead of decimal. Because Hex format exists only for integral values.
这篇关于为什么在十进制和十六进制之间转换会引发formatexception?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!