Search code examples
c++floating-pointmemcpyfloating-point-precisionfloating-point-conversion

floating point precision using memcpy C++


I have a tricky problem that I do not understand. I have an array of uint8_t that I need to convert to a 32 bit floating point. I am using memcpy to accomplish that...however the rounding seems to be off. Could someone please explain what is happening/a solution to this issue, thanks in advance. The coefficientByteSwap array contains two coefficients, one in the first four bytes, and other in the 2nd four bytes.

static float32_t coefficient[ALLSENSORS][NUM_QUADRATIC_FIELDS];
uint8_t coefficientByteSwap[8];


memcpy(&coefficient[sensor][2], &coefficientByteSwap[0], sizeof(float32_t));
memcpy(&coefficient[sensor][3], &coefficientByteSwap[4], sizeof(float32_t));

example:

coefficientByteSwap[0] = 0xE8
coefficientByteSwap[1] = 0x32
coefficientByteSwap[2] = 0xB5
coefficientByteSwap[3] = 0xBC

should be a floating point value of: -.022119 but when I print it out it comes out: -.022119000554


Solution

  • Your assumption is wrong. Look at this:

    float f = -.022119;
    std::cout << std::setprecision(20) << f << std::endl;
    

    Prints: -0.022119000554084778