user3856370 user3856370 - 16 days ago 5
C Question

Variable cast to double in printf produces random output

I was trying to see the hex representation of floating point numbers and compiled this code with gcc-4.9.2:

#include <stdio.h>

int main()
{
double i = 100;

printf("%f %x\n", i, (double)i);

return 0;
}


I was surprised to find that everytime I ran the code the hex value printed out changed. What is going on? How can I safely print the hex representation of a floating point number?

Answer

The %x format specifier requires an argument of type unsigned int. You're giving it an argument of type double. The behavior is undefined, which means that as far as the C standard is concerned anything can happen -- including changing the output for other specifiers in the same format string.

To print the hex representation of a floating-point number, copy it to an array of unsigned char and print the elements of the array.

Comments