如何将float或double类型的数据由Network排列方式转换成host排列方式?(在线等待) 由于ntohl()函数要求数据类型是ULONG,对于float或double我就不知道该怎么办了!请教各位:如何将float或double类型的数据由Network排列方式转换成host排列方式? 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 http://expert.csdn.net/Expert/topic/1671/1671314.xml?temp=.9532129 在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; }} 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;} 只是调换字节的顺序吗?我认为应该将每一bit的顺序都调换 强制转换是不行的,因为在由float转为 ULONG时,会舍掉小数部分而保留整数部分。还有,请问bhw98,上述程序运行时,为什么对于整数如:2.0000之类的数,运行结果是0.00000 float a;ULONG u;u=*(ULONG*)&a; 除了存在字节序问题,可能还存在位序问题。位序问题就是所谓的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词法分析 定制过IE的朋友请留步 旷世难题>破VISTA系统的注册表权限问题 分离视图的程序中,在工作者者线程中如何访问各个视图,得到各个视图的类指针?? 谁可以给我串口通信的原代码或有关着方面知识的网址??? 高分求救!! cvdf 怎样才能够把从图片中读取到的像素点的RGB值分别求出来 请教关于combo box的问题! 怎么为控件加一个ImageList的属性?? 我打不开文件!! 任意输入一个文件,怎样在逻辑盘查找到此文件?有完整的原代码? builer与make的区别,这是个困惑我许久许久的问题
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;
}
}
{
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;
}
还有,请问bhw98,上述程序运行时,为什么对于整数如:2.0000之类的数,运行结果是0.00000
u=*(ULONG*)&a;
============================================================================
提问题时标题要简明扼要地说明问题内容,切忌使用"急","求救"之类不能说明问题的标题
http://www.betajin.com/alphasun/index.htm 给我发信息请附带原帖地址
http://alphasun.18en.com/ http://shakingtoolkit.9126.com/
DocWizard C++程序文档自动生成工具 | Wave OpenGL | HttpProxy | AjaxParser词法分析