Portable serialisation of IEEE754 floating-point values

后端 未结 3 1843
悲&欢浪女
悲&欢浪女 2020-12-17 17:51

I\'ve recently been working on a system that needs to store and load large quantities of data, including single-precision floating-point values. I decided to standardise on

3条回答
  •  无人及你
    2020-12-17 17:56

    Much simpler, and depending on the same assumption as yours (which is that float and integer types have the same byte order, and is almost universally valid -- realistically you'll never encounter a system where it isn't true):

    #include 
    
    float htonf(float val) {
        uint32_t rep;
        memcpy(&rep, &val, sizeof rep);
        rep = htonl(rep);
        memcpy(&val, &rep, sizeof rep);
        return val;
    }
    

    Any reasonably good compiler will optimize away the two memcpy calls; they are present to defeat over-eager strict aliasing optimizations, so this ends up being as efficient as htonl plus the overhead of a single function call.

提交回复
热议问题