Saving floating point as binary

What are you guys recommendations as for a way to portably save floating points as binary?

The obvious approach would be to just cast it and dump the binary data:

1
2
3
4
5
double foo = whatever;

char* binary = static_cast<char*>(&foo);

file.write(binary,sizeof(double));


Although this has several problems:

1) Endian issues
2) sizeof() issues (what if double is a different size on another platform)
3) floating point encoding issues (what if floating point numbers have a different number of mantissa bits, etc on a different platform?)


#1 is easily solved, but #2,3 make this a bit more complicated.

Are they worth worrying about? Does anyone have thoughts as to how they can be overcome?
Unless your binary file format specifically indicates how your floating point values are to be saved and/or you intend to only use it on one particular platform or architecture, then you are much better off just storing them as strings.

If you want to handle endianness and format issues in a cross-platform way, you'll probably want to look at the frexp() and ldexp() functions in <cmath>, and write a routine to specifically read and write binary floating point data.

Good luck!
Topic archived. No new replies allowed.