1.在上报经纬度时由于数据协议限制需要将double型数据存储到无符号数组中,下边是写了一个简单C程序进行验证;
2.代码示例如下
#include <stdio.h>
typedef union
{
float data;
unsigned char arr[4];
} my_data;
int main()
{
my_data test_data = {0};
double jingdu = 121.4736522;
double weidu = 31.2425864;
test_data.data = jingdu;
//注意大小端问题
for(int i = 3; i >= 0; i--)
{
printf("1.test_data[%d] = %02X\n",i,test_data.arr[i]);
}
printf("\r\n");
test_data.data = weidu;
//注意大小端问题
for(int i = 3; i >= 0; i--)
{
printf("2.test_data[%d] = %02X\n",i,test_data.arr[i]);
}
printf("\r\n");
/* Write C code in this online editor and run it. */
printf("Hello, World! \n");
return 0;
}
3.运行结果
4.下边再提供一种参考别人的写法
gps_position_info.e = 121.4736522;
uint8_t buffer[128];
dDwordToBuf(gps_position_info.e,&buffer[i]);
//将一个DWORD的值写入四个连续内存BYTE中
void dDwordToBuf(float inDword, rt_uint8_t * _pBuf)
{
*_pBuf++ = *((rt_uint8_t *)(&inDword) +3);
*_pBuf++ = *((rt_uint8_t *)(&inDword) +2);
*_pBuf++ = *((rt_uint8_t *)(&inDword) +1);
*_pBuf = *((rt_uint8_t *)(&inDword));
}