Displaying floating point variable as a hex integer screws up neighbouring integer

后端 未结 2 1637
耶瑟儿~
耶瑟儿~ 2021-01-17 00:56

I have this simple program

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


        
相关标签:
2条回答
  • 2021-01-17 01:11

    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
    
    0 讨论(0)
  • 2021-01-17 01:13

    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.

    0 讨论(0)
提交回复
热议问题