6

I have the following code, which writes 6 floats to disk in binary form and reads them back:

#include <iostream>
#include <cstdio>

int main()
{
  int numSegs = 2;
  int numVars = 3;

  float * data = new float[numSegs * numVars];
  for (int i = 0; i < numVars * numSegs; ++i) {
    data[i] = i * .23;
    std::cout << data[i] << std::endl;
  }

  FILE * handle = std::fopen("./sandbox.out", "wb");

  long elementsWritten = 
    std::fwrite(data, sizeof(float), numVars*numSegs, handle);

    if (elementsWritten != numVars*numSegs){
      std::cout << "Error" << std::endl;
    }

    fclose(handle);
    handle = fopen("./sandbox.out", "rb");

    float * read = new float[numSegs * numVars];

    fseek(handle, 0, SEEK_SET);

    fread(read, sizeof(float), numSegs*numVars, handle);

    for (int i = 0; i < numVars * numSegs; ++i) {
      std::cout << read[i] << std::endl;
    }
}

It outputs:

0
0.23
0.46
0.69
0.92
1.15
0
0.23
0.46
0.69
0.92
1.15

When I load the file in a hexer, we get:

00 00 00 00 1f 85 6b 3e  1f 85 eb 3e d7 a3 30 3f
1f 85 6b 3f 33 33 93 3f  -- -- -- -- -- -- -- --

I want to be calculate the float value from the decimal directly. For example: 1f 85 6b 3e becomes 0.23 and 1f 85 eb 3e becomes 0.46.

I've tried a few "binary to float" calculators on the web. When I put in the hexadecimal representation of the number, 0x1f856b3e, in both calculators I get back 5.650511E-20 . But I thought the value should be 0.23 since I provided bytes 5-8 to the calculator and these bytes represent the second float written to disk.

What am I doing wrong?

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
  • How about 3e eb 85 1f ? – Ivarpoiss Mar 21 '14 at 19:23
  • Just as a note: serializing floats isn't the best idea if that data is going to used by other computers. The main reason for this is you don't know what kind of floating point format another computer/program might use. It's generally a better idea to serialize it as a fixed point number (made up of integers), then when deserializing convert back to floating point. – leetNightshade Mar 21 '14 at 23:41

1 Answers1

10

This is an endianness issue if you for example switch:

1f 85 6b 3e 

to:

3e 6b 85 1f

this will result in .23 when you convert it using one of your converters, for example I used IEEE 754 Converter and Floating Point to Hex Converter allows you to do double as well as single precision conversions.

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
  • @jakeliquorblues 5 upvotes for a question is a pretty good indication people thought it was an interesting question. Let me know if you have any questions. – Shafik Yaghmour Mar 21 '14 at 20:53