发送端: 将浮点数转换为字节数组
float floatNum;
unsigned char byteArry[sizeof(double)];
void Float2Byte(float floatNum, unsigned char* byteArry) {
char* pchar = (char*)&floatNum;
for (int i = 0; i < sizeof(float); i++) {
*byteArry = *pchar;
pchar++;
byteArry++;
}
}
Float2Byte(floatNum, byteArry);
Usart_SendString(USART1, byteArry);
接收端: 将一个字节数组转换为浮点数
float Byte2Float(unsigned char* byteArry) {
float floatNum;
memcpy(&floatNum, byteArry, sizeof(float));
return floatNum;
}
完整代码
#include <stdio.h>
#include <string.h>
float Byte2Float(unsigned char* byteArry) {
float floatNum;
memcpy(&floatNum, byteArry, sizeof(float));
return floatNum;
}
void Float2Byte(float floatNum, unsigned char* byteArry) {
char* pchar = (char*)&floatNum;
for (int i = 0; i < sizeof(float); i++) {
*byteArry = *pchar;
pchar++;
byteArry++;
}
}
int main() {
float floatNum = 0.14159123;
double doubleNum = 0.1415912323;
unsigned char byteArry[sizeof(double)];
Float2Byte(doubleNum, byteArry);
printf("Double: %.10lf\n", doubleNum);
printf("Bytes: ");
for (int i = 0; i < sizeof(double); i++) {
printf("%02X ", byteArry[i]);
}
printf("\n");
return 0;
}