Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 583
psihodelia Avatar asked Nov 23 '09 21:11

psihodelia


People also ask

How floats and doubles are stored in C?

While float has 32 bit precision for floating number (8 bits for the exponent, and 23* for the value), i.e. float has 7 decimal digits of precision. As double has more precision as compare to that of flot then it is much obvious that it occupies twice memory as occupies by the float data type.

Why are floating point numbers called double?

A double is named such because it is double the "precision" of a float. Really, what this means is that it uses twice the space of a floating point value -- if your float is a 32-bit, then your double will be a 64-bit.


Video Answer


1 Answers

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.

like image 198
Fabio Ceconello Avatar answered Oct 08 '22 20:10

Fabio Ceconello