How can I serialize doubles and floats in C?
I have the following code for serializing shorts, ints, and chars.
unsigned char * serialize_char(unsign
To start, you should never assume that short
, int
etc have the same width on both sides. It would be much better to use the uint32_t
etc (unsigned) types that have known width on both sides.
Then to be sure that you don't have problems with endianess there are the macros/functions ntoh
htos
etc that are usually much more efficient than anything you can do by your own. (on intel hardware they are e.g just one assembler instruction.) So you don't have to write conversion functions, basically they are already there, just cast your buffer
pointer to a pointer of the correct integer type.
For float
you may probably assume that they are 32 bit and have the same representation on both sides. So I think a good strategy would be to use a pointer cast to uint32_t*
and then the same strategy as above.
If you think you might have different representations of float
you would have to split into mantissa and exponent. Probably you could use frexpf
for that.
You can always use unions to serialize:
void serialize_double (unsigned char* buffer, double x) {
int i;
union {
double d;
unsigned char bytes[sizeof(double)];
} u;
u.d = x;
for (i=0; i<sizeof(double); ++i)
buffer[i] = u.bytes[i];
}
This isn't really any more robust than simply casting the address of the double
to a char*
, but at least by using sizeof()
throughout the code you are avoiding problems when a data type takes up more/less bytes than you thought it did (this doesn't help if you are moving data between platforms that use different sizes for double
).
For floats, simply replace all instances of double
with float
. You may be able to build a crafty macro to auto-generate a series of these functions, one for each data type you are interested in.