1

I'm finding my float value has changed after being returned. I output the hex value of the float before being returned and then after it gets returned. I expect the HEX output to be identical but they have changed. Can you please explain why this is happening and how do I prevent this from happening?

Thanks!

  #include <stdio.h>
  typedef int             uint32;
  typedef unsigned char   uint8;
  static const float CONST_FLOAT = 150.36e6;

  uint32 foo( uint8 param ) {
     return 1;
  }

  float get_float( uint8 param )
  {
       float fVal = 0.0;

       fVal = (foo( param )*1.0) / ( 60.0 * CONST_FLOAT );

       printf("fVal = 0x%X\n", fVal);
       printf("fVal = %f\n", fVal);

       return fVal;
  }

  int main(void) {
     float fTest;

     fTest = get_float(1);

     printf("fTest = 0x%X\n",fTest);
     printf("fTest = %f\n",fTest);

     return;
  }

OUTPUT: fVal = 0x6A96C728 fVal = 0.000000

fTest = 0x9AAF9000 fTest = 0.000000

I expect the fVal displayed in Hex format to be the same as fTest in Hex but they turned out different why is that?

Thanks!

user1144251
  • 327
  • 1
  • 3
  • 12

1 Answers1

3

You cannot print a float value with the "%x" specifier. It's undefined behavior, and your program is obviously behaving accordingly.

This is from the C11 draft 1570,

7.21.6.1 The fprintf function

  1. The conversion specifiers and their meanings are:

    o,u,x,X

    The unsigned int argument is converted to unsigned octal (o), unsigned decimal (u), or unsigned hexadecimal notation (x or X) in the style dddd; the letters abcdef are used for x conversion and the letters ABCDEF for X conversion. The precision specifies the minimum number of digits to appear; if the value being converted can be represented in fewer digits, it is expanded| with leading zeros. The default precision is 1. The result of converting a zero value with a precision of zero is no characters. ?

  2. If a conversion specification is invalid, the behavior is undefined. 282) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97