【问题标题】:int pointer to float pointer - reinterpret_cast指向浮点指针的 int 指针 - reinterpret_cast
【发布时间】:2021-07-26 06:00:23
【问题描述】:

以下是代码:

int a = 1;
int* ptr = &a;
float* p1 = (float*)ptr // or reinterpret_cast<float*>(ptr);
cout << *p1 << endl;

当我尝试打印浮点指针 p1 指向的值时,我得到的答案是:1.4013e-45。 谁能解释一下为什么会这样?

【问题讨论】:

  • 您期望什么价值,为什么?
  • 我希望得到“1”作为输出。
  • 迂腐的答案是这是未定义的行为。在纸面上,实际上任何事情都可能发生,而你无法控制。
  • IEEE-754 Floating Point Converter 0x00000001 代表 1.40129846432e-45
  • float f = a; 如果您希望将值分配给浮点数。 float 的位与 int 的位完全不同。

标签: c++ casting reinterpret-cast


【解决方案1】:

浮点或双精度表示中使用的整数值为denormal,并根据IEEE 754 standard进行转换。

【讨论】:

    【解决方案2】:

    谁能解释一下为什么会这样?

    你通过一个与指向对象的类型不兼容的指针来访问一个对象,因此程序的行为是不确定的。

    我希望得到“1”作为输出。

    要获得浮点数 1,您可以将 static_cast int 转换为浮点数,或者简单地让转换为隐式:

    float f = a;
    std::cout << f;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-07
      • 2015-09-10
      • 1970-01-01
      • 2016-03-27
      • 1970-01-01
      • 1970-01-01
      • 2017-09-03
      相关资源
      最近更新 更多