IEEE“double”的精确文本表示 [英] Exact textual representation of an IEEE "double"

查看:182
本文介绍了IEEE“double”的精确文本表示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要用人类可读的文本格式表示一个IEEE 754-1985双精度(64位)浮点数,条件是文本形式可以正确地解析回相同的(按位)数字。

这是可能的/实际的做,而不只是打印原始字节?
如果是的话,代码要做到这一点将不胜感激。

解决方案

最佳选择:使用C99十六进制浮点格式:

  printf(%a,someDouble); 

这种方式产生的字符串可以转换回 double 与C99 strtod()函数,还有 scanf()函数。其他几种语言也支持这种格式。一些例子:

 十进制数%a格式含义
------------- -------------------------------
2.0 0x1.0p1 1.0 * 2 ^ 1
0.75 0x1 .8p-1 1.5 * 2 ^ -1

十六进制格式的优点是所有的表示都是确切。因此,即使有人改变执行转换的舍入模式,将字符串转换回浮点也将始终给出原始数字。对于不精确的格式,这是不正确的。



如果您不想使用十六进制格式,并且愿意假设舍入模式将永远是圆到最近(默认),那么你可以摆脱格式化你的数据至少17位有效数字小数。如果你有一个正确的四舍五入的转换程序(大多数 - 不是所有的平台),这将保证你可以做一个从双倍到字符串的往返旅程,而不会损失任何准确性。


I need to represent an IEEE 754-1985 double (64-bit) floating point number in a human-readable textual form, with the condition that the textual form can be parsed back into exactly the same (bit-wise) number.

Is this possible/practical to do without just printing the raw bytes? If yes, code to do this would be much appreciated.

解决方案

Best option: Use the C99 hexadecimal floating point format:

printf("%a", someDouble);

Strings produced this way can be converted back into double with the C99 strtod( ) function, and also with the scanf( ) functions. Several other languages also support this format. Some examples:

decimal number    %a format     meaning
--------------------------------------------
2.0               0x1.0p1       1.0 * 2^1
0.75              0x1.8p-1      1.5 * 2^-1

The hexadecimal format has the advantage that all representations are exact. Thus, converting the string back into floating-point will always give the original number, even if someone changes the rounding mode in which the conversion is performed. This is not true for inexact formats.

If you don't want to use the hexadecimal format for whatever reason, and are willing to assume that the rounding mode will always be round to nearest (the default), then you can get away with formatting your data as decimals with at least 17 significant digits. If you have a correctly rounded conversion routine (most -- not all -- platforms do), this will guarantee that you can do a round trip from double to string and back without any loss of accuracy.

这篇关于IEEE“double”的精确文本表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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