将包含浮动的结构转换为更网络友好的结构

Ian*_*ung 5 c computer-science network-programming

我正在尝试通过网络发送包含浮点数据的结构,该结构包含两种不同的硬件架构,用 C 编写。

客户端运行在x86_64架构上,服务器运行在PPC(32位)架构上。

看来我将数据转换为网络友好格式或从网络友好格式转换为数据的唯一选项是:

htons/ ntohs(2 字节)和htonl/ ntohl(4 字节)

似乎没有处理浮点数的版本(这是有道理的,因为不同的体系结构/字节序有不同的浮点数表示)。

因此,我尝试通过以下方式将浮点数拆分为整数和指数格式:

void FtoME(float num, int32_t* mantissa, int32_t* exponent)
{
    int32_t sig = (int32_t)num;
    int32_t exp = 0;
    double frac = num-sig;
    double temp = num;
    while (frac > 0 && exp > -20)
    {
        temp = temp * 10; //left shift the whole number
        sig = (int32_t)temp; //get the integer part
        frac = temp - sig; //get the fractional part
        exp--;
    }
    printf("Scientific note: %dx10^%d\n",sig, exp);
    *mantissa = sig;
    *exponent = exp;
}
Run Code Online (Sandbox Code Playgroud)

现在,虽然这在理论上确实有效,但在实践中,我遇到了很多溢出,很明显,这不是处理这个问题的正确方法。

我是否可以尝试其他方法来避免溢出,并将浮点数转换为网络友好格式(重要的是,再次返回),同时不丢失任何数据?

Ant*_*ala 4

IEEE 754 标准对于大多数架构来说应该足够了 - 仅对于那些不兼容的架构,您只需要担心到 IEEE 754 的转换以及再次转换回来。对于字节顺序的东西,给定一个 32 位浮点数,您可以使用uint32_t tmp; memcpy(&tmp, &f, sizeof(f));htonlntohl