要将float型数据转换成字节进行传输
(2020-10-24 10:30:01)文章目录
一.前言
在与上位机之间进行数据收发,要将float型数据转换成字节进行传输,根据float型数据的存储方式可知:一个float型数据占用4字节存储空间。因此可将一个float型数据转换成4个字节数据进行传输。同样在接收端也可以将4字节转换成float型数据进行显示。本文给出了两种转换方法如下:
二.地址指针转换的方法
#include
#include
unsigned char byte[4];
int main()
{
int i;
unsigned char* Float_to_Byte(float f); //声明float转4字节函数
float Byte_to_Float(unsigned char *p); //声明4字节转float函数
float f = 3.1415,f1;
unsigned char *p;
p=Float_to_Byte(f); //进行float到4字节转换,并将转换结构存放在指针p中
printf("%x %x %x %x\r\n",*p,*(p+1),*(p+2),*(p+3));//打印转换出的字节结果
f1= Byte_to_Float(p); //将4字节转换成float
printf("float data=%f\n",f1); //打印转换结果
system("pause");
return 0;
}
unsigned char* Float_to_Byte(float f)
{
float float_data = 0;
unsigned long longdata = 0;
longdata = *(unsigned long*)&f; //注意,会丢失精度
byte[0] = (longdata & 0xFF000000) >> 24;
byte[1] = (longdata & 0x00FF0000) >> 16;
byte[2] = (longdata & 0x0000FF00) >> 8;
byte[3] = (longdata & 0x000000FF);
return byte;
}
float Byte_to_Float(unsigned char *p)
{
float float_data=0;
unsigned long longdata = 0;
longdata = (*p<< 24) + (*(p+1) << 16) + (*(p + 2) << 8) + (*(p + 3) << 0);
float_data = *(float*)&longdata;
return float_data;
}
#include
#include
unsigned char s[4];
int main()
{
int i;
float float_data=3.1415;
float floatdata; //转化后输出float
unsigned char *p;
unsigned char *float_to_char(float f, unsigned char *s); //声明float转unsigned char
float char_to_float(unsigned char *s); //声明unsigned char转float
p = float_to_char(float_data, s);
for (i = 0; i <</FONT> 4; i++)
printf("char[%d]=%d\n", i, *p++); //打印转化的四个四个字节
floatdata = char_to_float(s);
printf("floatdata=%f\n", floatdata);
system("pause");
return 0;
}
unsigned char *float_to_char(float f, unsigned char *s) //输入的float型数据,输出char存放地址
{
union change
{
float d;
unsigned char dat[4];
}r1;
r1.d = f;
*s = r1.dat[0];
*(s + 1) = r1.dat[1];
*(s + 2) = r1.dat[2];
*(s + 3) = r1.dat[3];
return s;
}
float char_to_float(unsigned char *s) //输入char存放地址
{
float f;
union change
{
float d;
unsigned char dat[4];
}r1;
r1.dat[0] = *s;
r1.dat[1]= *(s+1);
r1.dat[2] = *(s +2);
r1.dat[3] = *(s + 3);
f = r1.d;
return f;
}
前一篇:GNRMC解析