how to convert double between host and network byte order?

泄露秘密 提交于 2019-11-28 00:27:20

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

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);

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.

EDIT:

From the comment

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); 
}

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);
}

This might be hacky (the char* hack), but it works for me:

double Buffer::get8AsDouble(){

    double little_endian = *(double*)this->cursor;

    double big_endian;

    int x = 0;
    char *little_pointer = (char*)&little_endian;
    char *big_pointer = (char*)&big_endian;

    while( x < 8 ){
        big_pointer[x] = little_pointer[7 - x];
        ++x;
    }

    return big_endian;

}

For brevity, I've not include the range guards. Though, you should include range guards when working at this level.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!