Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 838
waffleman Avatar asked Jul 30 '13 13:07

waffleman


Video Answer


2 Answers

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, i.e. 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.

like image 98
David Heffernan Avatar answered Sep 18 '22 01:09

David Heffernan


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, [-]0xh.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.

like image 43
Eric Postpischil Avatar answered Sep 21 '22 01:09

Eric Postpischil