C语言实现浮点型数据与字节数组的相互转化

在实现串口通信或网络通信时,通常需要将数据转换为字节流的形式传输,此时需要进行数据格式转换。

MCU和PC的浮点数都是基于IEEE754格式的,有4字节(float)、8字节(double)。以双精度浮点型数据为例,分析强制指针类型转换的方法实现。

#include <stdio.h>

void double2bytes(double data, unsigned char* bytes);
double bytes2double(unsigned char bytes[]);

int main()
{
    double d1 = 3.14159;
    unsigned char b1[8];
    double2bytes(d1, b1);
    int i;
    for(i=0; i<8; i++)
    {
        printf("%02X ", b1[i]);
    }

    printf("\n");

    unsigned char b2[8] = {0x6E, 0x86, 0x1B, 0xF0, 0xF9, 0x21, 0x09, 0x40};
    double d2 = bytes2double(b2);
    printf("%f", d2);

    return 0;
}

/**
 * 双精度浮点型数据double转字节数组(小端模式)
 */
void double2bytes(double data, unsigned char bytes[])
{
    int i;
    char* p = (char*)&data;  //将double类型的指针强制转换为unsigned char型
    for(i=0; i<8; i++)
    {
        bytes[i] = *p++;  //将相应地址中的数据保存到unsigned char数组中
    }
}

/**
 * 字节数组转双精度浮点型数据double(小端模式)
 */
double bytes2double(unsigned char bytes[])
{
    double data = *((double *)bytes);  //直接将unsigned char型的指针强制转换为double类型
    return data;
}

输出:
6E 86 1B F0 F9 21 09 40 
3.141590
上一篇 Java认证与Shiro安全框架
下一篇 C++ ANSI及UTF-8与Unicode转码
目录
文章列表
1 Python及Go配置代理
Python及Go配置代理
2
利用XStream在Java对象和XML之间相互转换
利用XStream在Java对象和XML之间相互转换
3
npm及yarn设置和取消代理的方法
npm及yarn设置和取消代理的方法
4
Spring Cloud Alibaba 2.1.1 新特性Sidecar模块介绍
Spring Cloud Alibaba 2.1.1 新特性Sidecar模块介绍
5
Flutter页面间跳转和传参Navigator的使用
Flutter页面间跳转和传参Navigator的使用
最新评论
一位WordPress评论者
一位WordPress评论者
2月12日
您好,这是一条评论。若需要审核、编辑或删除评论,请访问仪表盘的评论界面。评论者头像来自 Gravatar。