cfloating-pointinternal-representation

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


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.


Solution

  • 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.