How do I reinterpret data through a different type? (type punning confusion)

前端 未结 3 1120
南笙
南笙 2020-12-19 10:47
#include 

int main(int argc, char * argv[])
{
    int a = 0x3f800000;

    std::cout << a << std::endl;

    static_assert(sizeof(float)         


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-19 11:18

    Use memcpy:

    memcpy(&f2, &a, sizeof(float));
    

    If you are worried about type safety and semantics, you can easily write a wrapper:

    void convert(float& x, int a) {
        memcpy(&x, &a, sizeof(float));
    }
    

    And if you want, you can make this wrapper template to satisfy your needs.

提交回复
热议问题