How can I convert 4 bytes storing an IEEE 754 floating point number to a float value in C?

前端 未结 3 1048
生来不讨喜
生来不讨喜 2020-12-18 11:14

My program reads into 4 bytes an IEEE 754 floating point number from a file. I need to portable convert those bytes to my C compilers float type. In other words I need a fun

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-18 12:07

    If the endianness is the same, then like so:

    float f;
    memcpy(&f, raw_value, sizeof f);
    return f;
    

    If not, say:

    float f;
    char * p = (char *)&f;
    

    And now populate the bytes p[0]... manually as needed.

提交回复
热议问题