[英]C - how to store IEEE 754 double and single precision
I have to work with IEEE 745 double and single precision numbers. 我必须使用IEEE 745双精度和单精度数字。 I have no idea, how to work with them correctly.
我不知道如何正确使用它们。
I've got a buffer of binary data and I want to get the numbers like 我有一个二进制数据缓冲区,我想获得像
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);
What do I put instead of IEE745double_t
and IEEE745single_t
? 我要代替
IEE745double_t
和IEEE745single_t
什么? Is it possible to do it with double and float? 是否可以使用double和float? And if so, how can I guarantee, that they will be 8 and 4 bytes long on every platform?
如果是这样,我如何保证在每个平台上它们的长度分别为8和4个字节?
First of all, you cannot do the pointer cast hack. 首先,您不能进行指针强制转换。 There is absolutely no guarantee that your byte buffer is correctly aligned.
绝对不能保证字节缓冲区正确对齐。 This results in undefined behaviour .
这导致不确定的行为 。 Use
memcpy
instead: 使用
memcpy
代替:
memcpy(&first8bytes, &buffer[8], 8);
memcpy(&next4bytes, &buffer[16], 4);
What do I put instead of
IEE745double_t
andIEEE745single_t
?我要代替
IEE745double_t
和IEEE745single_t
什么? Is it possible to do it with double and float?是否可以使用double和float?
Yes, it's possible, if : 是的, 如果有可能:
double
is 8 bytes, float
is 4 bytes and both use IEEE754 presentation. double
是8个字节, float
是4个字节,都使用IEEE754表示。 buffer
uses same byte order as your host. buffer
数据使用与主机相同的字节顺序。 If not, you need to copy to temporary unsigned integer type first, where you fix the endianness. And if so, how can I guarantee, that they will be 8 and 4 bytes long on every platform?
如果是这样,我如何保证在每个平台上它们的长度分别为8和4个字节?
Use static assertion to detect when it's not. 使用静态断言来检测何时不存在。 For example:
例如:
static_assert(sizeof(float) == 4, "invalid float size");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.