将float
值的位模式复制到uint32_t
或反之亦然(而不是它们),我们可以使用std::copy
或memcpy
复制位字节到字节。另一种方法是如下使用reinterpret_cast
:复制位模式:浮点数到uint32_t
float f = 0.5f;
uint32_t i = *reinterpret_cast<uint32_t*>(&f);
或
uint32_t i;
reinterpret_cast<float&>(i) = 10;
但是有一个claim是说,两名reinterpret_cast
上面使用,调用未定义的行为。
这是真的吗?怎么样?
正如答案所述,它是UB。一个断言“sizeof(uint32_t)== sizeof(float)'虽然应该是所有你需要确信它会起作用的。 – NathanOliver
@NathanOliver但是,如果编译器进行基于类型的别名优化,那么如果你不提供'-fno-strict-aliasing'或其他东西,它可以合理地破坏行为。 – TartanLlama
@TartanLlama好点。检查'alignof'也可能是需要的。 – NathanOliver