简体   繁体   中英

Storing floating point numbers in a file

For a C application that I am implementing, I need to be able to read and write a set of configuration values to a file. These values are floating point numbers. In the future it is possible that another application (could be written in C++, Python, Perl, etc...) will use this same data, so these configuration values need to be stored in a well defined format that is compiler and machine independent.

Byte order conversion functions ( ntoh/hton ) can be used to handle the Endianness, however what is the best way to get around the different meanings of "float" value? Is there are common method for storing floats? Rounding and truncating is not a problem, just as long as it is defined.

There are probably two main options:

  1. Store in text format. Here you would standardise on a particular format using a well-defined decimal separator and use scientific notation, ie 6.66e42 .
  2. Store in binary format using the IEEE754 standard. Use either the 4 or 8 byte data type. And as you noted, you'd have to settle on an endianness convention.

A text format is probably more portable because there are machines that do not natively understand IEEE754. That said, such machines are rare in these times.

The C formatted input/output functions have a format specifier for this, %a . It formats a floating-point number in a hexadecimal floating-point format, [-] 0x h . hhhhd . That is, it has a “-” sign if needed, hexadecimal digits for the fraction part, including a radix point, a “p” (for “power”) to start the exponent and a signed exponent of two (in decimal).

As long as your C implementation uses binary floating-point (or any floating-point such that its FLT_RADIX is a power of two), conversion with the %a format should be exact.

IEEE 754 , or ISO/IEC/IEEE 60559:2011, is the standard for floating point used by most languages.

For C, it's officially taken by standard in C11. (C11 Annex F IEC 60559 floating-point arithmetic )

For small amounts of data, such as configuration values, go with text not binary. If you want, go for structured text of some form, such as JSON, XML. Do decide on how many digits to write to represent a floating-point number according to your requirements.

As the range of required portability (across languages, operating systems, time, space, etc) increases so the force of the argument in favour of text becomes stronger.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM