gpt4 book ai didi

c++ - 复制位模式: float 到uint32_t

转载 作者:行者123 更新时间:2023-12-01 15:11:27 49 4
gpt4 key购买 nike

float值的位模式复制到uint32_t中,反之亦然(不强制转换),我们可以使用std::copymemcpy逐位复制位。另一种方法是使用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/

49 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com