Portable data reinterpretation

前端 未结 5 981
温柔的废话
温柔的废话 2020-11-30 09:28

I want to reinterpret data of one type as another type in a portable way (C99). I am not talking about casting, I want a reinterpretation of some given dat

5条回答
  •  無奈伤痛
    2020-11-30 09:29

    If you want to avoid the strict aliasing rule, you need to first cast to a char pointer:

    float float_value = 3.14;
    int *int_pointer = (int *)(char *)&float_value;
    int int_value = *int_pointer;
    

    Note however, that you might have sizeof(int) > sizeof(float), in which case you still get undefined behavior

提交回复
热议问题