【发布时间】:2015-07-20 12:03:15
【问题描述】:
我有两个进程在同一个设备上运行(不涉及虚拟机),通过二进制 IPC 协议进行通信。由于这保证了数字的表示对于发送者和接收者是相同的,我可以安全地假设以下序列化将适用于任何支持浮点数的设备吗?
void store_double(uint8_t *buf, double d)
{
memcpy(buf, &d, sizeof(double));
}
double load_double(uint8_t const *buf)
{
double d;
memcpy(&d, buf, sizeof(double));
return d;
}
double orig = 123.456;
uint8_t serialized[sizeof(double)];
store_double(serialized, orig);
// send serialized bytes to the receiver
// receive serialized bytes from the sender
double copy = load_double(serialized);
【问题讨论】:
-
由于您限制环境以避免字节顺序问题,我会说它是安全的(只要
buf足够长,这是您的情况)。 -
如果两端的硬件以 IEEE 双精度格式表示
double值,则字节序问题应该无关紧要:en.wikipedia.org/wiki/Double-precision_floating-point_format
标签: c++ c serialization floating-point ipc