0

我有float存储在 a 中的 a 的内部表示uint32_t。假设我们有两个具有这些条件。我想floats将由 表示的两者相加uint32_t,然后将它们的内部表示存储在另一个uint32_t中。我一直在尝试一些事情,但我不确定是否有一种简单或标准的方法。在我看来,有两个问题:

  1. 将存储在 中的内部表示转换uint32_t为 a float(否则我不知道如何对它们求和)。
  2. 求和后,将生成的float内部表示存储在 a 中uint32_t

我一直在研究 C 库中的函数,也许它可以用printf或者atof但我没有设法解决它。

4

2 回答 2

1

好吧,我终于用 memcpy() 解决了。我不完全确定它是否完全可靠,但我认为它运作良好。

//Generate the floats
float a = 1.0;
float b = 2.1;
uint32_t x;
uint32_t y;
//Copy the internal representation to x, y
memcpy(&x, &a, sizeof(float));
memcpy(&y, &b, sizeof(float));

//This would be the starter point of the problem described above
float c, d;
memcpy(&c, &x, sizeof(float));
memcpy(&d, &y, sizeof(float));

float r = c + d;
printf("The number is %f\n", r);

正如预期的那样,打印的数字是 3.1000。

于 2021-07-23T12:27:11.137 回答
1

我不明白您为什么使用类型化语言将内容存储在不兼容的容器中,但让我们看看这是否对您有帮助:

union flt_int {
    float    f;
    uint32_t i;
};

...

union flt_int a, b;

a.i = val1;  /* val1 is the integer internal rep of a float */
b.i = val2;  /* idem. */
c.f = a.f + b.f; /* use the floating point representation to add */
/* now you have in c.i the internal representation of the
 * float sum of a and b as a uint32_t */
于 2021-07-27T10:38:39.050 回答