首页 > 解决方案 > Reinterpret cast from float to int

问题描述

float f = 12.5;
unsigned int _f = *reinterpret_cast<int*>(&f);
std::cout << _f << std::endl; // result: 1095237632

Can some explain me how such casting works? And what is represented by _f?

EDIT So this number I got 1095237632 after converting to binary is 0b1000001010010000000000000000000 and this binary number is 12.5 in IEEE-754. Do I get it right?

标签: c++

解决方案


没有人可以解释(*),因为它不起作用。

cppreference

与 static_cast 不同,但与 const_cast 类似,reinterpret_cast 表达式不会编译为任何 CPU 指令(除非在整数和指针之间转换或在指针表示取决于其类型的晦涩架构上)。它纯粹是一个编译时指令,指示编译器将表达式视为具有 new_type 类型。

使用 reinterpret_cast 只能完成以下转换,除非此类转换会抛弃常量或易变性。

然后遵循一系列规则,涵盖允许重新解释强制转换的内容。将类型A转换为完全不相关的类型B不在其中,并且您的代码表现出未定义的行为。

(*) 严格来说不正确。您将浮点数视为 int,如果您查看它们在硬件上的表示,并且如果您检查编译器的输出,您可以弄清楚为什么会得到您得到的值,尽管未定义的行为是未定义的并且不值得输入详细信息除非您愿意编写不可移植的代码。


推荐阅读