gpt4 book ai didi

C中用union将串口数据转为float

转载 作者:太空宇宙 更新时间:2023-11-04 03:18:22 24 4
gpt4 key购买 nike

我在 Linux 上使用 C 程序从串口读取数据。

要读取的数据来自 Code Composer Studio 行:UART_writePolling(uartHandle, (uint8_t*) &value, sizeof(float));

value是我想在 C 中读取的 float ,其中 value = 1.5 .

当我从串口读入数据时,在 C 中,将数据读入缓冲区并使用 printf("%u\n", (int)buffer[i]); 打印

我得到 value成为:

0     
0
4294967232
63

当我插入 buffer[i] 时进入a.array并打印 printf("%d\n", a.array[i]);我得到 value成为:

0
0
-64
63

我也尝试过使用 union :

    unsigned int value = 0;
for (int j = 3; j >= 0; j--){
//value <<= 8;
value = value + (int)a.array[i+8+j];
}
printf("value: %u\n", value);
data.u = value;
printf("(float): %f\n", data.f);

没有给出正确答案。

如何使用 union 将正确的数据作为 float 获取?我需要使用 << 吗? ?

编辑:更好的代码思路

//headers

typedef struct {
int *array;
size_t used;
size_t size;
} Array;

void initArray(Array *a, size_t initialSize) {
a->array = (int *)malloc(initialSize * sizeof(int));
a->used = 0;
a->size = initialSize;
}
... //more functions/code to resize array and free the memory later

union Data {
float f;
unsigned int u;
};

int main(){
union Data data;

//open serial port code

char buffer[1]; /* Buffer to store the data received,
reading one at a time */

Array a;
initArray(&a, 5); /* initialise an array to store the read data
that is read into buffer*/

//while loop to read in data for some amount of time/data
int b_read = 0;
b_read = read(fd, &buffer, sizeof(buffer));

for (int i=0; i<b_read; i++){
printf("%u\n", (int)buffer[i]);
// how the first set of values above were printed

insertArray(&a, buffer[i]);
// also adding the values read to buffer into array a
}
//end while

// close the port

for(int i=0; i<no. of elements in array a; i++){
printf("%d\n", a.array[i]);
// how the second set of results were printed
}

//below is an attempt at using union and <<:
unsigned int value = 0;
for (int j = 3; j >= 0; j--){
//value <<= 8;
value = value + (int)a.array[i+8+j]; //index used is particular to my code, where value is in a specific place in the array
}
printf("value: %u\n", value);
data.u = value;
printf("(float): %f\n", data.f);
//these printfs don't give a reasonable answer

// free memory

return 0;
}

最佳答案

一旦字节进入buffer从偏移量开始 i ,您可以将字节重新解释为 float :

float f;
memcpy(&f, buffer+i, sizeof f);

要使用 union ,您可以使用:

union { uint32_t u; float f; } x;
x.u = value;
float f = x.f;

但是,这需要 value包含代表 float 的所有 32 位.当您尝试使用以下方法构造值时:

//value <<= 8;
value = value + (int)a.array[i+8+j];

有两个问题。一、value <<= 8是需要的。我想你先试过了,没有得到正确答案,所以你把它注释掉了。但是,这是必需的。其次,这段代码将字节一个一个地插入到 value 中。是顺序相关的。一旦移位恢复,它会将寻址较大的字节插入到 value 的较低有效位中。 .系统通常按以下两种顺序之一排列对象中的字节:较低地址中的较高有效字节或较高地址中的较高有效字节。我们不知道您的系统使用哪种顺序,因此我们不知道您将地址较大的字节插入较低有效字节的代码是否正确。

注意:以上假定字节以相同的顺序读取和写入,或者字节顺序问题已在其他代码中处理。

关于C中用union将串口数据转为float,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49175251/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com