Convert the internal representation of a float stored in an integer to an actual float

127 Views Asked by At

I have the internal representation of a float stored in a uint32_t. Suppose we have two of them with those conditions. I want to sum the two floats represented by the uint32_t and then store their internal representation inside another uint32_t. I've been trying a few things but I'm not sure if there is an easy or standard way of doing so. From my point of view, there are two problems:

  1. Convert the internal representation stored in the uint32_t to a float (otherwise I wouldn't know how to sum them).
  2. After the sum, store the resulting float internal representation in a uint32_t.

I've been looking at functions in C libraries and maybe it could be done with printf or atof but I have not managed to resolve it.

2

There are 2 best solutions below

2
On BEST ANSWER

Well, I finally used memcpy() to solve it. I am not entirely sure that it is completely reliable but I think it works well.

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

The number printed is 3.1000 as expected.

0
On

I don't understand why you use a typed language to store things in incompatible containers, but let's see if this if of help to you:

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 */