Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exact textual representation of an IEEE "double"

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.

like image 360
Vladimir Panteleev Avatar asked Mar 19 '10 21:03

Vladimir Panteleev


1 Answers

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.

like image 156
Stephen Canon Avatar answered Oct 07 '22 05:10

Stephen Canon