So apparently on my machine, float, double and long double each have different sizes each. There also doesn’t seem to be a strict standard enforcing how many bytes each of those types would have to be.
How would one, then, save a floating point value into a binary file, and then have it read properly on a different system if the sizes differ? e.g my machine has 8 byte doubles, whereas joe’s have 12 byte doubles.
Without having to export it in text form (e.g “0.3232”), that is. Seems a lot less compact than the binary representation.
You have to define a format, and implement that. Typically, most of the
network protocols I know use IEEE float and double, output big-endian
(but other formats are possible). The advantage of using IEEE formats
is that it is what most of the current everyday machines use
internally; if you’re on one of these machines (and portability of your
code to other machines, like mainframes, isn’t an issue), you can
“convert” to the format simply by type-punning to an unsigned int of the
same size, and outputting that. So, for example, you might have:
If you have to be portable to a machine not supporting IEEE (e.g. any of
the modern mainframes), you’ll need something a bit more complicated:
(Note that this doesn’t handle NaN’s and infinities correctly.
Personally, I would ban them from the format, since not all floating
point representations support them. But then, there’s no floating point
format on an IBM mainframe which will support 1E306, either, although
you can encode it in the IEEE double format above.)
Reading is, of course, the opposite. Either:
or if you can’t count on IEEE:
(This assumes that the input is not an NaN or an infinity.)