Serialize double and float with C

后端 未结 8 1253
孤街浪徒
孤街浪徒 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条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-01 10:27

    I remember first seeing the cast used in my example below in the good old Quake source code of the "rsqrt" routine, containing the coolest comment I'd seen at the time (Google it, you'll like it)

    unsigned char * serialize_float(unsigned char *buffer, float value) 
    { 
        unsigned int ivalue = *((unsigned int*)&value); // warning assumes 32-bit "unsigned int"
        buffer[0] = ivalue >> 24;  
        buffer[1] = ivalue >> 16;  
        buffer[2] = ivalue >> 8;  
        buffer[3] = ivalue;  
        return buffer + 4; 
    } 
    

    I hope I've understood your question (and example code) correctly. Let me know if this was usefull?

提交回复
热议问题