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
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
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.