uart数据传输-float类型转为char类型和char类型转为float类型
#include <iostream>
#include <vector>
using namespace std;
//由float类型转为char
void Float2Byte(vector<float> floatnum, unsigned char* byteArry)
{
*byteArry = 0XAB;
*(byteArry + 1) = 0XCD;
for (int i = 0; i < sizeof(float); i++)
{
*(byteArry + 2 + i) = *((char*)&floatnum[0] + i); //第一个float数据的首地址转为char类型的首地址
*(byteArry + 6 + i) = *((char*)&floatnum[1] + i); //第二个float数据的首地址转为char类型的首地址
*(byteArry + 10 + i) = *((char*)&floatnum[2] + i); //第三个float数据的首地址转为char类型的首地址
}
*(byteArry + 14) = 0XEF;
*(byteArry + 15) = 0XCA;
}
//由char类型转为float
void Byte2Float(vector<float> &floatnum, unsigned char* byteArry)
{
if((*byteArry == 0XAB) && (*(byteArry + 1) == 0XCD) && (*(byteArry + 14) == 0XEF) && (*(byteArry + 15) == 0XCA))
{
floatnum[0] = *(float*)(byteArry + 2); //接收,反解出float数据类型
floatnum[1] = *(float*)(byteArry + 6);
floatnum[2] = *(float*)(byteArry + 10);
}
}
//测试
int main()
{
unsigned char* bArry = new unsigned char[16]; //定义长度为16char的指针。
vector<float> num1 = {-12.51f, 10.12f, 45.01f}; //赋初值
vector<float> num2 = {0,0,0};
for (int i = 0; i < 10; i++)
{
Float2Byte(num1, bArry); //float类型转为char类型
cout << "num1[0] = " << num1[0] << " " << "num1[1] = " << num1[1] << " " << "num1[2] = " << num1[2] << endl;
Byte2Float(num2, bArry); //char类型转为float类型
cout << "num2[0] = " << num2[0] << " " << "num2[1] = " << num2[1] << " " << "num2[2]= " << num2[2] << endl;
}
delete [] bArry; //释放内存
return 0;
}