在小尾数法和大尾数法之间有效转换 [英] Convert between little-endian and big-endian floats effectively
问题描述
我有一个可以运行的软件,当前可以在 little-endian
架构上运行。我也想使其在 big-endian
模式下运行。我想将 little-endian
数据写入文件中,而不管底层系统的字节顺序如何。
I have a working software, which currently runs on a little-endian
architecture. I would like to make it run in big-endian
mode too. I would like to write little-endian
data into files, regardless of the endianness of the underlying system.
To为实现这一目标,我决定使用boost endian库。它可以有效地转换整数。
To achieve this, I decided to use the boost endian library. It can convert integers efficiently. But it cannot handle floats (and doubles).
它在文档, Boost 1.59.0将支持浮点类型 。但是 1.62
仍不支持它们。
It states in the documentation, that "Floating point types will be supported in the Boost 1.59.0". But they are still not supported in 1.62
.
我可以假设,浮点数有效 IEEE 754
浮动(或加倍)。但是它们的字节序可能会根据基础系统而有所不同。据我所知,不建议在浮点数上使用 htonl
和 ntohl
函数。那怎么可能呢?是否有任何仅标头的库,它也可以处理浮点数?我找不到任何东西。
I can assume, that the floats are valid IEEE 754
floats (or doubles). But their endianness may vary according to the underlying system. As far as I know, using the htonl
and ntohl
functions on floats is not recommended. How is it possible then? Is there any header-only library, which can handle floats too? I was not able to find any.
我可以将浮点数转换为字符串,然后将其写入文件,出于多种原因,我想避免使用该方法(性能,磁盘空间,...)
I could convert the floats to string, and write that into a file, I would like to avoid that method, for many reasons ( performance, disk-space, ... )
推荐答案
序列化float / double值时,我做出以下三个假设: / p>
When serializing float/double values, I make the following three assumptions:
- 机器表示遵循IEEE 754
- float / double的字节序与整数的字节序
- double& / int64_t&之间的reinterpret_cast-ing行为或float& / int32_t&是明确定义的(例如,强制转换的行为就像类型是相似的一样)。
这些假设均无法通过标准得到保证。在这些假设下,以下代码将确保双精度型使用little-endian编写:
None of these assumptions is guaranteed by the standard. Under these assumptions, the following code will ensure doubles are written in little-endian:
ostream out;
double someVal;
...
static_assert(sizeof(someVal) == sizeof(int64_t),
"Endian conversion requires 8-byte doubles");
native_to_little_inplace(reinterpret_cast<int64_t&>(someVal));
out.write(reinterpret_cast<char*>(&someVal), sizeof(someVal));
这篇关于在小尾数法和大尾数法之间有效转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!