指数基数为 10 的 double 和 float 的 c 代码序列化
我需要一个快速的解决方案来将浮点型(4 字节)和双精度型(8 字节)序列化为二进制表示形式,以便通过网络发送它们。
问题是我必须使用的格式:
尾数 * 10^指数
,其中尾数是有符号整数(对浮点数进行编码时为 4 个字节,对双精度数进行编码时为 8 个字节),指数以 1 个字节进行编码。
指数以 10 为基数,因此位移位技巧对我来说似乎毫无用处,我必须将尾数与指数网分开才能将它们序列化。
任何建议将不胜感激
I need a fast solution to serialize float (4 bytes) and double (8 bytes) into binary representation to send them over the network.
The problem is the format I have to use :
mantissa * 10^exponent
where the mantissa is a signed integer (4 bytes when encoding the float and 8 bytes for the double) and the exponent is coded on 1 byte.
The exponent is a base 10, so bit shifting tricks seem useless to me and I have to separate the mantissa from the exponenet in order to serialize them.
Any suggestion would be appreciated
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您关于编码尾数是整数的说法让我感到困惑。它必须表示某种形式的浮点数,可能以四个或八个字节编码。
对于任何正数 x,您可以将
x
唯一地表示为其中
n
是整数,并且0 <= f << 1.
.请注意,根据定义。
对于正数x,我能想到的最简单的代码是这样的:
对于负数
x
,在应用上面的代码之前需要取绝对值,然后对符号进行编码无论哪种方式都是合适的。其成本是三个不平凡的浮点运算,但我现在这些都是在通用 CPU 上的硬件中完成的。您仍然需要解决将尾数编码为四字节或八字节值的问题。
Your statement that the encoded mantissa is an integer confuses me. It has to represent some form of a floating point number, perhaps encoded in four or eight bytes.
For any positive number x, you can uniquely express
x
aswhere
n
is an integer, and0 <= f < 1
. Note thatby definition.
For positive x, the simplest code I can imagine is this:
For negative
x
, you need to take the absolute value before applying the above code, and then encode the sign in whatever way is appropriate.The cost of this is three non-trivial floating point operations, but I these are all done in hardware these days on general-purpose CPUs. You still have to solve the problem of encoding the mantissa into a four or eight byte value.
为什么你需要看代表性?
如何在连接的两端使用 htonl 和 ntohl 函数,并以二进制形式发送它们。
why do you need to look at the representation?
How about using the htonl and ntohl functions at the respective ends of your connections, and send them in binary.