C - 浮点数的序列化(浮点数、双精度数) [英] C - Serialization of the floating point numbers (floats, doubles)

查看:39
本文介绍了C - 浮点数的序列化(浮点数、双精度数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将浮点数转换为字节序列,以便可以持久化到文件中?这种算法必须快速且高度可移植.它还必须允许相反的操作,反序列化.如果每个值(持久空间)只需要非常微小的多余位,那就太好了.

How to convert a floating point number into a sequence of bytes so that it can be persisted in a file? Such algorithm must be fast and highly portable. It must allow also the opposite operation, deserialization. It would be nice if only very tiny excess of bits per value (persistent space) is required.

推荐答案

假设您使用的是主流编译器,C 和 C++ 中的浮点值遵循 IEEE 标准,并且当以二进制形式写入文件时,可以在任何其他平台,前提是您使用相同的字节字节序进行写入和读取.所以我的建议是:选择一个字节序,在写之前或者读之后,检查这个字节序是否和当前平台的一样;如果没有,只需交换字节.

Assuming you're using mainstream compilers, floating point values in C and C++ obey the IEEE standard and when written in binary form to a file can be recovered in any other platform, provided that you write and read using the same byte endianess. So my suggestion is: pick an endianess of choice, and before writing or after reading, check if that endianess is the same as in the current platform; if not, just swap the bytes.

这篇关于C - 浮点数的序列化(浮点数、双精度数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆