方法1:转化成整型传输
假如保留float类型数据为两位小数,我们可以将float数据*100,转换成整型数据传输,对端收到后,再/100,转换成float类型。
方法2:直接传输
例如:传输float类型占4个字节,大端序传输
以下环境为windows 系统下的 Qt 编译:
1、.pro中添加
LIBS += -lws2_32
2、cpp中添加头文件
#include <WinSock2.h>
3、程序代码
#include <WinSock2.h>
typedef union{
float f;
unsigned int i;
}UN_FANDI;
float htonf(float f)
{
UN_FANDI un_fandi;
un_fandi.f=f;
un_fandi.i=htonl(un_fandi.i);
return un_fandi.f;
}
int main()
{
printf("大端序:\n");
//float类型数据写入报文
uchar ch[4];
float fValue = 3.14,fRetValue;
fRetValue = htonf(fValue);
memcpy(ch,&fRetValue,4);
//显示的报文
printf("%02x,%02x,%02x,%02x\n",ch[0],ch[1],ch[2],ch[3]);
//解析报文为float类型数据
UN_FANDI unValue;
memcpy(&unValue.i,ch,4);
unValue.i = htonl(unValue.i);
printf("%.2f\n",unValue.f);
printf("**************\n");
printf("小端序:\n");
//float类型数据写入报文
uchar ch_1[4];
float fValue_1 = 3.14;
memcpy(ch_1,&fValue_1,4);
//显示的报文
printf("%02x,%02x,%02x,%02x\n",ch_1[0],ch_1[1],ch_1[2],ch_1[3]);
//解析报文为float类型数据
float fVlalue_2;
memcpy(&fVlalue_2,ch_1,4);
printf("%.2f\n",fVlalue_2);
fflush(stdout);
return 0;
}
程序运行结果:
总结:
1)、float类型其实是可以直接传输的;
2)、我们利用共用体的形式,将float类型进行了字节序转换,如果是小端序传输,则不必转换了。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)