Serialize double and float with C

后端 未结 8 1252
孤街浪徒
孤街浪徒 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:15

    The portable way: use frexp to serialize (convert to integer mantissa and exponent) and ldexp to deserialize.

    The simple way: assume in 2010 any machine you care about uses IEEE float, declare a union with a float element and a uint32_t element, and use your integer serialization code to serialize the float.

    The binary-file-haters way: serialize everything as text, floats included. Use the "%a" printf format specifier to get a hex float, which is always expressed exactly (provided you don't limit the precision with something like "%.4a") and not subject to rounding errors. You can read these back with strtod or any of the scanf family of functions.

提交回复
热议问题