将float
值的位模式复制到uint32_t
中,反之亦然(不强制转换),我们可以使用std::copy
或memcpy
逐位复制位。另一种方法是使用reinterpret_cast
如下(?):
float f = 0.5f;
uint32_t i = *reinterpret_cast<uint32_t*>(&f);
要么
uint32_t i;
reinterpret_cast<float&>(i) = 10;
但是,有一个claim表示上面使用的两个
reinterpret_cast
会调用未定义的行为。真的吗?怎么样?
最佳答案
是的,这是未定义的行为,因为它违反了严格的别名规则:
[basic.lval]/10:
If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined — the dynamic type of the object,— a cv-qualified version of the dynamic type of the object,
— a type similar (as defined in 4.4) to the dynamic type of the object,
— a type that is the signed or unsigned type corresponding to the dynamic type of the object,
— a type that is the signed or unsigned type corresponding to a cv-qualified version of the dynamic type of the object,
— an aggregate or union type that includes one of the aforementioned types among its elements or non- static data members (including, recursively, an element or non-static data member of a subaggregate or contained union),
— a type that is a (possibly cv-qualifded) base class type of the dynamic type of the object,
— a char or unsigned char type.
由于在尝试访问
uint32_t
类型的对象时,float
并非以上所述,因此行为未定义。
关于c++ - 复制位模式: float 到uint32_t,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38744365/