This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

Trouble with converting a long to a float

Hi Folks,

I hope this is an easy one to solve but I'm having trouble converting a long into a float.  From what I've been able to glean from the docs a long and float are both 32 bits.  Using the debugger I can see that if I assign 0.12345 to a variable the hex value is 0x3DFCD35B.  And if I assign the same number to the long the debugger shows the same hex value as the float.

So, the question is - how do I convert the long into the float?  Casting the long to float isn't working.

float myTestData;
int32_t numToTest;

numToTest = 0x3dfcd35b; // equal to 0.12345

myTestData = (float)numToTest;


Using the debugger, myTestData ends up equal to 0x4E77F34D which is 1.316484e+09 and not the expected hex value of 0x3DFCD35B. What do I need to change to get this working?

Thanks,

Richard Cooke

  • Hi Richard,

    What you are looking for is to have the compiler "interpret" the number as float. What you are doing instead is "converting" it to float. If your integer was 0x00000001 (1) and you cast to float you get 1.0 (0x3f800000)

    The long integer 0x3dfcd35b is 1039979355 in decimal. When you assign this number to a float variable the compiler assumes you want to convert it to a floating point representation so the float variable gets 1039979355 .0, but since this number is not exactly representable in floating point you get the closest number to it, which is 1.03997933E9 (0x4e77f34d).....you can check this on

    plug in 1039979355.0 and you will see the closest representation. So if you want to instead just interpret the hex, you do this

    typedef union{
      float f32;
      int32_t i32;
    }numToTest;
    
    float myTestData;
    
    numToTest.i32 = 0x3dfcd35b;
    
    myTestData = numToTest.f32;

  • small correction

    typedef union{
      float f32;
      int32_t i32;
    }myType_t;
    
    myType_t numToTest;
    float myTestData;
    
    numToTest.i32 = 0x3dfcd35b;
    
    myTestData = numToTest.f32;

  • Vishal,


    That worked so thank you so much.  This was driving me crazy.  I guess it's time to dig out the old C manuals again and read up on some of the esoteric parts of the C language.

    Thanks again,

    Richard