Mar*_*ork 6 c++ floating-point double ieee-754
IEEE 754浮点格式是否跨平台定义良好?在位格式和字节顺序方面?
我愿意在我的代码中添加以下内容(初始版本):
static_assert(std::numeric_limits<float>::is_iec559, "Only support IEC 559 (IEEE 754) float");
static_assert(sizeof(float) * CHAR_BIT == 32, "Only support float => Single Precision IEC 559 (IEEE 754)");
static_assert(std::numeric_limits<double>::is_iec559, "Only support IEC 559 (IEEE 754) double");
static_assert(sizeof(float) * CHAR_BIT == 64, "Only support double => Double Precision IEC 559 (IEEE 754)");
static_assert(std::numeric_limits<long double>::is_iec559, "Only support IEC 559 (IEEE 754) long double");
static_assert(sizeof(float) * CHAR_BIT == 128, "Only support long double => Exteneded Precision IEC 559 (IEEE 754)");
// More asserts if required.
// I noticed my current system has a sizeof(long double) => 128
// But numeric_limits<long double>::digits => 63
// So we are not storing quad precision floats only extended.
Run Code Online (Sandbox Code Playgroud)
如果我用二进制格式写我的float/double/long double,它们可以在系统之间传输而无需进一步解释.即...
void write(std::ostream& stream, double value)
{
stream.write(reinterpret_cast<char const*>(&value), 8);
}
....
double read(std::istream& stream)
{
double value;
stream.read(reinterpret_cast<char*>(&value), 8);
return value;
}
Run Code Online (Sandbox Code Playgroud)
或者我是否需要将双重分解成整数组件以进行传输(如本答案所示):
这里的区别是我愿意将我支持的表示限制为IEEE-754这是否基本上解决了浮点值的二进制存储问题,还是需要采取进一步措施?
注意:对于不符合要求的平台(当我找到它们时)我愿意特殊情况下的代码,以便他们将IEEE-754读/写成本地表示.但我想知道bit/endian是否足够好定义跨平台以支持存储/传输.
位格式是明确定义的,但并非所有机器都是小尾数法。IEEE 标准也不要求浮点数采用特定的字节序。您可以运行以下程序来查看 的字节模式double 42.0:
#include <stdio.h>
#include <numeric>
#include <limits>
using namespace std;
int main() {
double d = 42;
printf("%i\n", std::numeric_limits<double>::is_iec559);
for (char *c = (char *)&d; c != (char *)(&d+1); c++) {
printf("%02hhx ", *c);
}
printf("\n");
}
Run Code Online (Sandbox Code Playgroud)
在使用 g++ 3.4.5 的旧的、未维护的 Sun 机器上,此打印
1
40 45 00 00 00 00 00 00
Run Code Online (Sandbox Code Playgroud)
在运行更新版本 g++ 的 x86_64 机器上:
1
00 00 00 00 00 00 45 40
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1785 次 |
| 最近记录: |