串口通信,收发十六进制

发送端: 将浮点数转换为字节数组

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 
#include 

// 将一个字节数组转换为浮点数
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");

  /*  float floatNum1 = Byte2Float(byteArry);
    printf("Float: %f\n", floatNum1);*/

    return 0;
}

你可能感兴趣的:(嵌入式软件开发,c++,算法,开发语言)