【发布时间】:2020-11-11 02:30:23
【问题描述】:
这是一个简化的 C++ 程序,将 4 个字节转换为其 IEE754 浮点表示。
#include <iostream>
#include <math.h>
#include <memory.h>
uint8_t bytes[4] = {0x40, 0xd5, 0xc6, 0x7f}; // 0x40d5c67f
float f;
int main()
{
memcpy(&f, &bytes[0], 4);
printf("%.*lf", 5, f);
}
它的输出是nan! isnan 也为它返回 true。这是怎么发生的? 0x40d5c67f is 6.6804...
发生在我的类似 arduino 的微控制器和 http://cpp.sh/
【问题讨论】:
-
你的机器是什么?
-
@MikeCAT 好点,在类似 arduino 的微控制器和 cpp.sh 上进行了测试。已添加到问题中。
-
也欢迎将 4 个字节转换为浮点数的更好方法 :)
-
如果你使用
uint32_t bytes = UINT32_C(0x40d5c67f);和memcpy(&f, &bytes, 4);怎么办? -
@MikeCAT 是的,解决了它!我很想知道为什么
标签: c++ floating-point nan