C - Serialization of the floating point numbers (floats, doubles)

psihodelia picture psihodelia · Nov 23, 2009 · Viewed 16.5k times · Source

How to convert a floating point number into a sequence of bytes so that it can be persisted in a file? Such algorithm must be fast and highly portable. It must allow also the opposite operation, deserialization. It would be nice if only very tiny excess of bits per value (persistent space) is required.

Answer

Fabio Ceconello picture Fabio Ceconello · Nov 23, 2009

Assuming you're using mainstream compilers, floating point values in C and C++ obey the IEEE standard and when written in binary form to a file can be recovered in any other platform, provided that you write and read using the same byte endianess. So my suggestion is: pick an endianess of choice, and before writing or after reading, check if that endianess is the same as in the current platform; if not, just swap the bytes.