Why do I get ridiculous floating point values when I read a binary file?

Started by
16 comments, last by Matias Goldberg 10 years, 8 months ago

mesh 1: 238 1 104 26 float value: 0.517633


I can't think of any way to interpret those 4 bytes as a float anywhere near 0.517633: Any floating-point number between 0.5 and 1.0 should start with a byte with the value 63. Your second bytes are all 0 or 1, which seems suspicious. Perhaps you are looking in the wrong part of the file?
Advertisement

Before reading the value print the result of a ftell() function. This will be the offset the code is reading.

Open the file in the hex editor and find what is the values there.

You may use an reverse code to print what the float should actually be, for instance:


    uint8_t array[4] = {0x99, 0x83, 0x04, 0x3f}; // here you put the 4 bytes on the offset being read.
    float* fp = array;
    printf("%f\n", *fp);

This will print 0.517633.

BTW: Are you checking for errors in you file read, open, write operations? Did you remember to call close in the program that created the binary file?

Currently working on a scene editor for ORX (http://orx-project.org), using kivy (http://kivy.org).

I think you may be (embarrassingly) right. Does this look more like a float to you?

3F DA 30 F5

Here it prints: -224187207951651397809339904294912.000000.

But the reversed value 0xF5 0x30 0xDA 0x3F prints 1.704619

Are you sure the order isn't reversed?

Currently working on a scene editor for ORX (http://orx-project.org), using kivy (http://kivy.org).

The value you have there is correct when you reversed the byte order (1.704619). How would I make that work in code?

Something like this:


    uint8_t array[sizeof(float)]
    read(array, sizeof(float), 1, filepointer);
    
    uint8_t reverseArray[sizeof(float)];
    for (int i = 0; i < sizeof(float); ++i){
        reverseArray[i] = array[sizeof(float)-i-1];
    }


    float* fp = reverseArray;
    printf("%f\n", *fp);

Currently working on a scene editor for ORX (http://orx-project.org), using kivy (http://kivy.org).

Thank you everybody who posted a reply your responses have been very useful. I think i'll tinker with it by myself to try and find the solution.

Try:


d.dword_value = ((uint32_t)b[0] << 24) |
		((uint32_t)b[1] << 16) |
		((uint32_t)b[2] << 8) |
		((uint32_t)b[3]);

I'm quite sure the order was messed up

This topic is closed to new replies.

Advertisement