IEEE754浮点值的便携式系列化 [英] Portable serialisation of IEEE754 floating-point values
问题描述
我最近一直在努力,需要存储和加载大量数据,包括单precision浮点值的系统上。我决定在网络字节顺序标准化整数,并决定将储存浮点值big-endian格式,即:
I've recently been working on a system that needs to store and load large quantities of data, including single-precision floating-point values. I decided to standardise on network byte order for integers, and also decided to store floating point values in big-endian format, i.e.:
|-- Byte 0 --| |-- Byte 1 -| Byte 2 Byte 3
# ####### # ####### ######## ########
Sign Exponent Mantissa
1b 8b, MSB first 23b, MSB first
在理想情况下,我想提供像 htonl函数()
和 ntohl()
,因为我已经使用这些用于擦拭整数,我也希望有尽可能多的平台无关性越好(而假设浮动
类型对应IEEE754 32的方式来实现这一位浮点值)。有没有一些方法,可能使用 ieee754.h
,要做到这一点?
Ideally, I want to provide functions like htonl()
and ntohl()
, since I have already been using these for swabbing integers, and I also want to implement this in a way that has as much platform-independence as possible (while assuming that the float
type corresponds to IEEE754 32-bit floating point values). Is there some way, possibly using ieee754.h
, to do this?
我有一个答案似乎的工作,我会发布它下面,但它似乎pretty慢,效率低,我想AP preciate如何使任何建议它更快和/或更可靠。
I have one answer that seems to work, and I will post it below, but it seems pretty slow and inefficient and I would appreciate any suggestions about how to make it faster and/or more reliable.
推荐答案
简单得多,并且根据同样的假设和你(其是浮点和整数类型具有相同的字节顺序,并且是几乎普遍有效的 - 现实的你永远不会遇到一个系统,这是不正确的):
Much simpler, and depending on the same assumption as yours (which is that float and integer types have the same byte order, and is almost universally valid -- realistically you'll never encounter a system where it isn't true):
#include <string.h>
float htonf(float val) {
uint32_t rep;
memcpy(&rep, &val, sizeof rep);
rep = htonl(rep);
memcpy(&val, &rep, sizeof rep);
return val;
}
任何相当不错的编译器将优化掉两个的memcpy
通话;他们是present击败过于急切严格别名优化,所以这最终是为 htonl
高效加一个函数调用的开销。
Any reasonably good compiler will optimize away the two memcpy
calls; they are present to defeat over-eager strict aliasing optimizations, so this ends up being as efficient as htonl
plus the overhead of a single function call.
这篇关于IEEE754浮点值的便携式系列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!