java - 通过套接字跨网络传输 float

标签 java c++ networking floating-point network-programming

我们有一个TCP/IP 套接字 软件,包括一个Java 客户端C++ 服务器。通过套接字的数据包含数字、int、floatchar 数组。这些 float 的精度是点后的四位。最近,我们开始使用char array 来表示数据结构/协议(protocol)中的float 或int 来表示float(按时间10000 将float 转换为int,然后在接收端除以10000 ) 因为精度。

有人告诉我,如果我们直接在数据结构/协议(protocol)中使用 float ,则很难保持精度。发送方很难将精确的 float 放入套接字中,接收方也很难接收/转换回精确的 float 。

我不信。通过阅读 Wiki再次。看来单精度 float 可以提供6-9精度:

This gives from 6 to 9 significant decimal digits precision (if a decimal string with at most 6 significant decimal is converted to IEEE 754 single precision and then converted back to the same number of significant decimal, then the final string should match the original; and if an IEEE 754 single precision is converted to a decimal string with at least 9 significant decimal and then converted back to single, then the final number must match the original [3]).

如果所需的精度为 4 或 6,那么通过 Internet 传输 float 的最佳做法是什么?不止于此呢?双倍的!?。银行如何处理更大的 float ?

最佳答案

The precision of these floats are four digits after the point.

不,不是。您的 float 根本没有“[小数] 点后的四个 [小数] 数字”。它们有未知数量的二进制数字,这是您无法控制的。你所有的乘以和除以 10000 都不会也不能改变它,因为小数位和二进制位是不可比较的。如果您想要固定的小数精度,则必须使用小数基数。

Recently, we started to use either char array to represent float in data structure/protocol or int to represent float (float to int by time 10000 and then divide 10000 on receiver side) because of the precision.

完全是浪费你的时间。往上看。另见 here为证。

I was told it is difficult to keep the precision if we use float inside the data structure/protocol directly. The sender is hard to put exactly float into the socket and the receiver is hard to receive/convert back to the exact float number.

你被误导了。您可以使用 DataOutputStream 和 DataInoutStream 的 API 以相同的方式将 float 以二进制形式直接放到线上,格式化和恢复它。但是,您根本不应该使用 float 。

What's the good practice to transfer float across the internet if the required precision is 4 or 6?

这个问题体现了术语上的矛盾。

How banks handle bigger floating point numbers?

他们不使用它们。

关于java - 通过套接字跨网络传输 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16674664/

相关文章:

java - 如何使用java在数组中获取用户输入?

java - Java SE 6 或 Java SE 7 中是否有非最终字段

java - 了解 Java 内存模型和垃圾收集

c++ - 继承自 shared_ptr<void>

linux - 有什么 Linux 命令可以查看进程正在下载的文件的 URL?

php - 是什么让 PHP 的 mail() 函数如此缓慢?

java - Android - eclipse 中的<终止>

c++ - 更改最近文件的总数

c++ - boost 池 malloc() 和 free() 编译器错误

基于Python的Socket程序接受libPcap(C-based)