-1

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

user2494298
  • 299
  • 3
  • 7
  • 23

1 Answers1

3

Your assumption is wrong. Look at this:

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

Prints: -0.022119000554084778

Photon
  • 3,182
  • 1
  • 15
  • 16
  • 5
    @user2494298: It's like the error you get representing 2/3 in decimal. It repeats infinitely, so you have to cut it off somewhere. – Fred Larson Dec 15 '14 at 22:02