【发布时间】:2011-04-28 20:02:26
【问题描述】:
我正在尝试用它的 4 个复合字节构建一个 32 位浮点数。有没有比使用以下方法更好(或更便携)的方法?
#include <iostream>
typedef unsigned char uchar;
float bytesToFloat(uchar b0, uchar b1, uchar b2, uchar b3)
{
float output;
*((uchar*)(&output) + 3) = b0;
*((uchar*)(&output) + 2) = b1;
*((uchar*)(&output) + 1) = b2;
*((uchar*)(&output) + 0) = b3;
return output;
}
int main()
{
std::cout << bytesToFloat(0x3e, 0xaa, 0xaa, 0xab) << std::endl; // 1.0 / 3.0
std::cout << bytesToFloat(0x7f, 0x7f, 0xff, 0xff) << std::endl; // 3.4028234 × 10^38 (max single precision)
return 0;
}
【问题讨论】:
-
考虑到这是我在 Stack Overflow 上的第一个问题,我对各种回复感到非常兴奋。我感谢大家的意见。
标签: c++ floating-point endianness portability single-precision