假如保留float类型数据为两位小数,我们可以将float数据*100,转换成整型数据传输,对端收到后,再/100,转换成float类型。
方法2:直接传输例如:传输float类型占4个字节,大端序传输
以下环境为windows 系统下的 Qt 编译:
1、.pro中添加
LIBS += -lws2_32
2、cpp中添加头文件
#include
3、程序代码
#includetypedef 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,%02xn",ch[0],ch[1],ch[2],ch[3]); //解析报文为float类型数据 UN_FANDI unValue; memcpy(&unValue.i,ch,4); unValue.i = htonl(unValue.i); printf("%.2fn",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,%02xn",ch_1[0],ch_1[1],ch_1[2],ch_1[3]); //解析报文为float类型数据 float fVlalue_2; memcpy(&fVlalue_2,ch_1,4); printf("%.2fn",fVlalue_2); fflush(stdout); return 0; }
程序运行结果:
总结:1)、float类型其实是可以直接传输的;
2)、我们利用共用体的形式,将float类型进行了字节序转换,如果是小端序传输,则不必转换了。



