Why does converting between decimal and hex throw a formatexception?

时间秒杀一切 提交于 2021-01-29 07:46:26

问题


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

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));
    }
}

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


回答1:


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

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.

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




回答2:


Change your code to:

int result = 1454787509433225637;


来源:https://stackoverflow.com/questions/20666474/why-does-converting-between-decimal-and-hex-throw-a-formatexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!