Portable way to serialize float as 32-bit integer

前端 未结 2 479
花落未央
花落未央 2021-01-12 10:04

I have been struggling with finding a portable way to serialize 32-bit float variables in C and C++ to be sent to and from microcontrollers. I want the format to be well-def

2条回答
  •  孤街浪徒
    2021-01-12 10:46

    Assuming the float is in IEEE 754 format, extracting the mantissa, exponent and sign, is completely portable:

    uint32_t internal;
    float value = //...some value
    memcpy( &internal , &value , sizeof( value ) );
    

    const uint32_t sign =     ( internal >> 31u ) & 0x1u;
    const uint32_t mantissa = ( internal >> 0u  ) & 0x7FFFFFu;
    const uint32_t exponent = ( internal >> 23u ) & 0xFFu;
    

    Invert the procedure to construct the float.

    If you want to send the entire float only, then just copy it to the buffer. This will work even if float is not IEEE 754, but it must be 32 bit and the endianess of both integer and floating point types must be the same:

    buffer[0] = ( internal >> 0u  ) & 0xFFu;
    buffer[1] = ( internal >> 8u  ) & 0xFFu;
    buffer[2] = ( internal >> 16u ) & 0xFFu;
    buffer[3] = ( internal >> 24u ) & 0xFFu;
    

提交回复
热议问题