C - 如何存储 IEEE 754 双精度和单精度

C - how to store IEEE 754 double and single precision

我必须使用 IEEE 745 双精度和单精度数字。 我不知道如何正确使用它们。

我有一个二进制数据缓冲区,我想得到像

这样的数字
uint8_t bufer[] = {................};
//data I want are at 8th position, (IEEE745_t is my imaginary format)
IEEE745double_t first8bytes = *(IEEE745double_t*)(buffer + 8);
IEEE745single_t next4bytes = *(IEEE745single_t*)(buffer + 16);

我应该用什么代替 IEE745double_tIEEE745single_t?是否可以用 double 和 float 来做?如果是这样,我如何保证它们在每个平台上都是 8 和 4 字节长?

首先,您不能进行指针转换 hack。绝对不能保证您的字节缓冲区正确对齐。这会导致 未定义的行为 。使用 memcpy 代替:

memcpy(&first8bytes, &buffer[8], 8); 
memcpy(&next4bytes, &buffer[16], 4); 

What do I put instead of IEE745double_t and IEEE745single_t? Is it possible to do it with double and float?

是的,有可能,if:

  • double 是 8 个字节,float 是 4 个字节,都使用 IEEE754 表示。
  • buffer 上的数据使用与您的主机相同的字节顺序。如果不是,则需要先复制到临时无符号整数类型,并在其中修复字节顺序。

And if so, how can I guarantee, that they will be 8 and 4 bytes long on every platform?

使用静态断言来检测何时不是。例如:

static_assert(sizeof(float) == 4, "invalid float size");