Code:
#include <stdio.h>
int main()
{
printf(
" %f, %u, %x,\n", 1.0f, 1.0f, 1.0f);
return 0;
}
Output: 1.000000, 1072693248, 0,
Code:
#include <stdio.h>
int main()
{
printf(
" %x, %f, %u,\n", 1.0f, 1.0f, 1.0f);
return 0;
}
Output: 3ff00000, 0.000000, 0
Code:
#include <stdio.h>
int main()
{
printf(
" %x, %u, %f,\n", 1.0f, 1.0f, 1.0f);
return 0;
}
Output: 3ff00000, 0, 1.000000
Is this just an issue with the number of bytes that %u and %x consume, and how do I get the values to become consistent?
Passing arguments whose type does not match the corresponding component of the format string will lead to undefined results, as you’ve noticed. In particular,
"%x"and"%u"both expect values of type (unsigned)int. Passing afloat(which will often actually be represented as adoubleorlong doubledepending on the ABI) is semantically incorrect.Your compiler should be warning you about this – if not, make sure you’ve got all warnings enabled (
-Wallfor GCC).If you want 1.0f as an integer, just cast:
If you’re trying to obtain the binary representations, try something like this: