由于ntohl()函数要求数据类型是ULONG,对于float或double我就不知道该怎么办了!
请教各位:
如何将float或double类型的数据由Network排列方式转换成host排列方式?

解决方案 »

  1.   

    http://expert.csdn.net/Expert/topic/1671/1671314.xml?temp=.9532129
      

  2.   

    在win32里,ULONG是4个字节,float也是4个字节,float可通过强制类型转换直接用ntohl():
    float a=1.8f;
    float b=(float)ntohl((float)a);自己写对称颠倒的代码:float ftohl(float x)
    {
      char tmp;
      char* p = (char*)&x;    // 指向首字节  for(int i = 0; i < 2; i++)
      {
        tmp = *(p+i);
        *(p+i) = *(p+(3-i));
        *(p+(3-i)) = tmp;
      }
    }
    double dbtohl(double x)
    {
      char tmp;
      char* p = (char*)&x;    // 指向首字节  for(int i = 0; i < 4; i++)
      {
        tmp = *(p+i);
        *(p+i) = *(p+(7-i));
        *(p+(7-i)) = tmp;
      }
    }
      

  3.   

    sorry,以上写法有误,更正为float ftohl(float x)
    {
      char tmp;
      char* p = (char*)&x;    // 指向首字节  for(int i = 0; i < 2; i++)
      {
        tmp = *(p+i);
        *(p+i) = *(p+(3-i));
        *(p+(3-i)) = tmp;
      }  return x;
    }
    double dbtohl(double x)
    {
      char tmp;
      char* p = (char*)&x;    // 指向首字节  for(int i = 0; i < 4; i++)
      {
        tmp = *(p+i);
        *(p+i) = *(p+(7-i));
        *(p+(7-i)) = tmp;
      }  return x;
    }
      

  4.   

    只是调换字节的顺序吗?我认为应该将每一bit的顺序都调换
      

  5.   

    强制转换是不行的,因为在由float转为 ULONG时,会舍掉小数部分而保留整数部分。
    还有,请问bhw98,上述程序运行时,为什么对于整数如:2.0000之类的数,运行结果是0.00000
      

  6.   

    float a;ULONG u;
    u=*(ULONG*)&a;
      

  7.   

    除了存在字节序问题,可能还存在位序问题。位序问题就是所谓的most significant bit leads,或者 less significant bit leads。在硬件设计中非常注意这个问题。但是在网络中,可能连接inet的系统的位序都是一样的。这是有可能的。不同的CPU字节序是不一样的,比如intel和motorola的字节序刚好相反。
    ============================================================================
    提问题时标题要简明扼要地说明问题内容,切忌使用"急","求救"之类不能说明问题的标题
    http://www.betajin.com/alphasun/index.htm          给我发信息请附带原帖地址
    http://alphasun.18en.com/                    http://shakingtoolkit.9126.com/
    DocWizard C++程序文档自动生成工具 | Wave OpenGL | HttpProxy | AjaxParser词法分析