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

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

问题描述

有人能告诉我如何双precision转换成网络字节顺序。
我试过

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我发现双浮子precision格式重新presentations( HTTP ://en.wikipedia.org/wiki/Double_$p$pcision ),但没有字节顺序出现。

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.

所以,我更AP preciate如果有人可以帮助我走出这个(C code将是巨大的!)。
注意:操作系统是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.

然后你可以声明函数

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

的实施只依赖你的编译器/ plattform的。结果
最好应使用一些的自然的定义,
所以你可以在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); 
}

这可以工作,但很明显,只有在两个平台使用相同的编码模式双,如果INT有长期的大小相同。结果
顺便说一句。返回值的方法是有点奇怪。

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.

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

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天全站免登陆