如何在主机和网络字节顺序之间转换双精度? [英] how to convert double between host and network byte order?

查看:22
本文介绍了如何在主机和网络字节顺序之间转换双精度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我如何将双精度转换为网络字节顺序.我试过

Could somebody tell me how to convert double precision into network byte ordering. I tried

uint32_t htonl(uint32_t hostlong);
uint16_t htons(uint16_t hostshort);
uint32_t ntohl(uint32_t netlong);
uint16_t ntohs(uint16_t netshort);

函数,它们运行良好,但它们都没有进行双(浮点)转换,因为这些类型在每个架构上都不同.通过 XDR 我发现了双浮点精度格式表示(http://en.wikipedia.org/wiki/Double_precision) 但没有字节排序.

functions and they worked well but none of them does double (float) conversion because these types are different on every architecture. And through the XDR i found double-float precision format representations (http://en.wikipedia.org/wiki/Double_precision) but no byte ordering there.

所以,如果有人能帮我解决这个问题,我将不胜感激(C 代码会很棒!).注意:操作系统为 Linux 内核 (2.6.29),ARMv7 CPU 架构.

So, I would much appreciate if somebody helps me out on this (C code would be great!). NOTE: OS is Linux kernel (2.6.29), ARMv7 CPU architecture.

推荐答案

你可以看看 IEEE 754 在交换浮点格式.

You could look at IEEE 754 at the interchanging formats of floating points.

但关键应该是定义一个网络顺序,例如.1. 字节指数和符号,字节 2 到 n 作为尾数,以 msb 顺序排列.

But the key should be to define a network order, ex. 1. byte exponent and sign, bytes 2 to n as mantissa in msb order.

然后你可以声明你的函数

Then you can declare your functions

uint64_t htond(double hostdouble);
double ntohd(uint64_t netdouble);

实现仅取决于您的编译器/平台.
最好应该使用一些自然定义,所以你可以在 ARM 平台上使用简单的转换.

The implementation only depends of your compiler/plattform.
The best should be to use some natural definition, so you could use at the ARM-platform simple transformations.

来自评论

static void htond (double &x)
{
  int *Double_Overlay; 
  int Holding_Buffer; 
  Double_Overlay = (int *) &x; 
  Holding_Buffer = Double_Overlay [0]; 
  Double_Overlay [0] = htonl (Double_Overlay [1]); 
  Double_Overlay [1] = htonl (Holding_Buffer); 
}

这可以工作,但显然只有当两个平台对 double 使用相同的编码模式并且 int 具有相同的 long 大小时.
顺便提一句.返回值的方式有点奇怪.

This could work, but obviously only if both platforms use the same coding schema for double and if int has the same size of long.
Btw. The way of returning the value is a bit odd.

但是你可以写一个更稳定的版本,像这样(伪代码)

But you could write a more stable version, like this (pseudo code)

void htond (const double hostDouble, uint8_t result[8])
{
  result[0] = signOf(hostDouble);
  result[1] = exponentOf(hostDouble);
  result[2..7] = mantissaOf(hostDouble);
}

这篇关于如何在主机和网络字节顺序之间转换双精度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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