Serialize double and float with C

后端 未结 8 1268
孤街浪徒
孤街浪徒 2020-12-01 09:47

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         


        
8条回答
  •  猫巷女王i
    2020-12-01 10:36

    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.

提交回复
热议问题