串行通讯是以字节为单位进行传送的,对于浮点数和整型数都需要进行转换才能进行通讯。
MCU和PC的浮点数都是基于IEEE754格式的。有4字节(float)、8字节(double)、10字节(有一些不支持)。这里以4字节(float)浮点数为例。
转化常见的方法有:
一、强制指针类型转换。
// 转换Int数据到字节数组
unsigned int intVariable,i;
unsigned char charArray[2];
(unsigned char) * pdata = ((unsigned char)*)&intVariable; //进行指针的强制转换
for(i=0;i<2;i++)
{
charArray[i] = *pdata++;
}
/
/ 转换float数据到字节数组
unsigned int i;
float floatVariable;
unsigned char charArray[4];
(unsigned char) * pdata = ((unsigned char)*)&floatVariable; //进行指针的强制转换
for(i=0;i<4;i++)
{
charArray[i] = *pdata++;
}
// 转换字节数组到int数据
unsigned int intVariable="0";
unsigned char i;
void *pf;
pf =&intVariable;
(unsigned char) * px = charArray;
unsigned int i;
float floatVariable;
unsigned char charArray[4];
(unsigned char) * pdata = ((unsigned char)*)&floatVariable; //进行指针的强制转换
for(i=0;i<4;i++)
{
charArray[i] = *pdata++;
}
// 转换字节数组到int数据
unsigned int intVariable="0";
unsigned char i;
void *pf;
pf =&intVariable;
(unsigned char) * px = charArray;
for(i=0;i<2;i++)
{
*(((unsigned char)*)pf+i)=*(px+i);
}
// 转换字节数组到float数据
float floatVariable="0";
unsigned char i;
void *pf;
pf =&floatVariable;
(unsigned char) * px = charArray;
for(i=0;i<4;i++)
{
*(((unsigned char)*)pf+i)=*(px+i);
}
二、使用结构和联合,这是我最喜欢的方法
{
*(((unsigned char)*)pf+i)=*(px+i);
}
// 转换字节数组到float数据
float floatVariable="0";
unsigned char i;
void *pf;
pf =&floatVariable;
(unsigned char) * px = charArray;
for(i=0;i<4;i++)
{
*(((unsigned char)*)pf+i)=*(px+i);
}
二、使用结构和联合,这是我最喜欢的方法
定义结构和联合如下
typedef union {struct {unsigned char low_byte;
unsigned char mlow_byte;
unsigned char mhigh_byte;
unsigned char high_byte;
}float_byte;
struct {unsigned int low_word;
unsigned int high_word;
}float_word;
float value;
字符串数组怎么转成byte }FLOAT;
typedef union {
struct {
unsigned char low_byte;
typedef union {struct {unsigned char low_byte;
unsigned char mlow_byte;
unsigned char mhigh_byte;
unsigned char high_byte;
}float_byte;
struct {unsigned int low_word;
unsigned int high_word;
}float_word;
float value;
字符串数组怎么转成byte }FLOAT;
typedef union {
struct {
unsigned char low_byte;
unsigned char high_byte;
} d1;
unsigned int value;
} INT;
} d1;
unsigned int value;
} INT;
使用方法:
对于浮点数:
FLOAT floatVariable;在程序中直接使用floatVariable.float_byte.high_byte,floatVariable.float_byte.mhigh_byte,
floatVariable.float_byte.mlow_byte,floatVariable.float_byte.low_byte这四个字节就可以方便的进行转换了。
对于整数:
INT intVariable;在程序中直接使用intVariable.value.high_byte,intVariable.value.low_byte就OK了。
三、对整型数可以用数学运算的方法进行转换
unsigned int intVariable;
unsigned char low_byte = intVariable%256;
unsigned char high_byte = intVariable/256;
unsigned char low_byte = intVariable%256;
unsigned char high_byte = intVariable/256;
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论