c++ - 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?
解决方案
没有人可以解释(*),因为它不起作用。
与 static_cast 不同,但与 const_cast 类似,reinterpret_cast 表达式不会编译为任何 CPU 指令(除非在整数和指针之间转换或在指针表示取决于其类型的晦涩架构上)。它纯粹是一个编译时指令,指示编译器将表达式视为具有 new_type 类型。
使用 reinterpret_cast 只能完成以下转换,除非此类转换会抛弃常量或易变性。
然后遵循一系列规则,涵盖允许重新解释强制转换的内容。将类型A
转换为完全不相关的类型B
不在其中,并且您的代码表现出未定义的行为。
(*) 严格来说不正确。您将浮点数视为 int,如果您查看它们在硬件上的表示,并且如果您检查编译器的输出,您可以弄清楚为什么会得到您得到的值,尽管未定义的行为是未定义的并且不值得输入详细信息除非您愿意编写不可移植的代码。
推荐阅读
- php - Drupal 站点显示 Index.php 文件的内容
- javascript - 如何在客户端 javascript 应用程序中隐藏凭据
- zsh - 有条件地在 zsh 中获取脚本
- django - 我在 Django 中收到 No such table 错误
- javascript - 使用 React 增加选择的价值
- javascript - 单击链接时如何使我的汉堡菜单消失
- excel - 需要用户表单命令按钮上的工具提示
- sql-server - 我想知道如何使用 CTE 在 Sql 服务器中分离数字字符和特殊字符?
- sql - 我们如何最大限度地减少获得 ORA-14766:无法获得稳定的元数据快照的机会
- c# - 如何在 asp.net core 3.1 中使用来自 asp.net framework 4.8 的 StatisticFormula 类