Reputation: 12424
So I have an unsigned integer Q with the value of 0xfccd11c0.
When I print it with printf("%i", Q);
I get -53669440 which is the signed integer representation of 0xfccd11c0 so I get it.
But when I print it with printf("%i", (double)Q);
I get 939524096. I DO know that in order to print a double value you need to use %f
as the string format, but still, what happens when converting to double that is causing that value to be printed?
Upvotes: 2
Views: 116
Reputation: 283614
Q is 4241297856
(double)Q has 64-bit IEEE-754 representation 0x41EF99A238000000
In little-endian, the lower 4 bytes of this occupy the same space as (int)Q would.
0x38000000 is 939524096
Handy online converter: http://babbage.cs.qc.edu/courses/cs341/IEEE-754.html
Upvotes: 4
Reputation: 32786
Please see an answer of mine to a similar question: How does the function printf works in C?. Basically the C compiler executes integer and floating-point operations on two different sets of registries, and printf
extracts it's arguments from the registries corresponding to the format string. This is one of the reasons that causes printf
's weird behaviours when the format string and the passed arguments don't match.
Note that this happens for a reduced number of arguments, when the compiler optimisations place the arguments in the available registries instead of placing them on the stack.
Upvotes: 0
Reputation: 31545
Here, Q is explicitly converted (by you) to a new memory object, let's call it Q_dbl
. It's passed to the printf
function, but as you specified %i
parameter, this chunk of memory is interpreted as an integer. That's an idea of what happens at low level.
unsigned int Q = 0xfccd11c0;
printf("%i", Q);
printf("%i", (double)Q);
auto Q_dbl = (double)Q;
printf("%f", Q_dbl);
printf("%i", Q_dbl);
Code is not tested.
Upvotes: 1
Reputation: 215
You can easy simulate what happens with this code:
unsigned int Q = 0xfccd11c0;
double dQ = (double)Q;
int *x = (int*)(&dQ);
*x now is equal to 939524096.
Upvotes: 0
Reputation: 28654
Using wrong format specifier in function such as printf
triggers undefined behaviour; in which case anything could happen.
Upvotes: 4