我一直在努力寻找一种可移植的方法来序列化 C 和 C++ 中的 32 位浮点变量,以便将其发送到微控制器或从微控制器发送。我希望格式定义得足够好,以便序列化/反序列化也可以从其他语言完成,而不需要太多的努力。相关问题有:
C++ 中 double/float 类型二进制序列化的可移植性
使用 C 序列化 double 和 float
C++ long 到 double 的可移植转换
I know that in most cases a typecast union/memcpy will work just fine because the float representation is the same, but I would prefer to have a bit more control and piece of mind. What I came up with so far is the following:
void serialize_float32(uint8_t* buffer, float number, int32_t *index) {
int e = 0;
float sig = frexpf(number, &e);
float sig_abs = fabsf(sig);
uint32_t sig_i = 0;
if (sig_abs >= 0.5) {
sig_i = (uint32_t)((sig_abs - 0.5f) * 2.0f * 8388608.0f);
e += 126;
}
uint32_t res = ((e & 0xFF) << 23) | (sig_i & 0x7FFFFF);
if (sig < 0) {
res |= 1 << 31;
}
buffer[(*index)++] = (res >> 24) & 0xFF;
buffer[(*index)++] = (res >> 16) & 0xFF;
buffer[(*index)++] = (res >> 8) & 0xFF;
buffer[(*index)++] = res & 0xFF;
}
and
float deserialize_float32(const uint8_t *buffer, int32_t *index) {
uint32_t res = ((uint32_t) buffer[*index]) << 24 |
((uint32_t) buffer[*index + 1]) << 16 |
((uint32_t) buffer[*index + 2]) << 8 |
((uint32_t) buffer[*index + 3]);
*index += 4;
int e = (res >> 23) & 0xFF;
uint32_t sig_i = res & 0x7FFFFF;
bool neg = res & (1 << 31);
float sig = 0.0;
if (e != 0 || sig_i != 0) {
sig = (float)sig_i / (8388608.0 * 2.0) + 0.5;
e -= 126;
}
if (neg) {
sig = -sig;
}
return ldexpf(sig, e);
}
The frexp and ldexp函数似乎是为此目的而设计的,但如果它们不可用,我尝试使用常见的函数手动实现它们:
float frexpf_slow(float f, int *e) {
if (f == 0.0) {
*e = 0;
return 0.0;
}
*e = ceil(log2f(fabsf(f)));
float res = f / powf(2.0, (float)*e);
// Make sure that the magnitude stays below 1 so that no overflow occurs
// during serialization. This seems to be required after doing some manual
// testing.
if (res >= 1.0) {
res -= 0.5;
*e += 1;
}
if (res <= -1.0) {
res += 0.5;
*e += 1;
}
return res;
}
and
float ldexpf_slow(float f, int e) {
return f * powf(2.0, (float)e);
}
我一直在考虑的一件事是使用 8388608 (2^23) 还是 8388607 (2^23 - 1) 作为乘数。文档说 frexp 返回大小小于 1 的值,经过一些实验后,似乎 8388608 给出的结果与实际浮点数是位精确的,我找不到任何溢出的极端情况。不过,对于不同的编译器/系统来说,情况可能并非如此。如果这可能成为一个问题,那么较小的乘数会稍微降低精度,这对我来说也很好。我知道这不能处理 Inf 或 NaN,但目前这不是必需的。
所以,最后,我的问题是:这看起来是一个合理的方法,还是我只是在制定一个仍然存在可移植性问题的复杂解决方案?