串口通信,收发十六进制

发布时间:2024年01月09日

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

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");

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

    return 0;
}
文章来源:https://blog.csdn.net/shouchen1/article/details/132069835
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。