Question

I have this simple program

#include <stdio.h>
int main(void)
{
 unsigned int a = 0x120;
 float b = 1.2;
 printf("%X %X\n", b, a);
 return 0;
}

I expected the output to be

some-value 120  (some-value will depend on the bit pattern of `float b` )

But I see

40000000 3FF33333

Why is the value of a getting screwed up? %X treats its arguments as signed int and hence it should have retrieved 4 bytes from the stack and printed the calue of b and then fetching the next 4 bytes print the value of a which is 0x120

Was it helpful?

Solution

Firstly, it's undefined behaviour to pass arguments to printf not matching the format specifiers.

Secondly, the float is promoted to double when passed to printf, so it's eight bytes instead of four. Which bytes get interpreted as the two unsigned values expected by the printf format depends on the order in which the arguments are pushed.

OTHER TIPS

If you want to see the bits of a stored float, use a union:

 float b = 1.2;
 union {
      float  f;
      int    i;
 } u;
 u.f = b;

 printf ("%x\n", u.i);

results (32-bit x86):

3f99999a
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top