Converting from int to float to C change value
Hey. I am trying to convert from int
to float
to C and for some reason the cast changes the value and I'm not sure why. So:
fprintf (stderr, "%d,%d\n", rgbValues->green, (float)rgbValues->green);
creates two different numbers. Please note that rgbValues->green
is int
.
Any idea why this is happening?
thank
source to share
You must say this in your format string. Using:
fprintf(stderr, "%d,%f\n", rgbValues->green, (float)rgbValues->green);
^
instead:
fprintf(stderr, "%d,%d\n", rgbValues->green, (float)rgbValues->green);
^
Note the change from d
to f
(the circumflex is ^
not part of the code, but just an indicator of where to look).
source to share
The format specifier %d
says printf
, "pops the next 4 bytes of the stack, interprets them as an integer, and prints out that integer." Since you are actually passing float
as a parameter, the bytes float
(which are stored in the IEEE-754 format ) become misinterpreted as an integer, hence different values. (In fact, it is float
converted to double
because of argument advancement in variadic functions, and it is the first 4 bytes that have advanced double
, which are interpreted as an integer.)
The correct solution is to use one of %e
, %f
or %g
format specifiers instead of %d
when printing float
. %e
says "Remove the next 8 bytes from the stack, interpret them as double
and print using scientific (exponential) notation" will %f
print using fixed point format and %g
print whichever is less %e
or %f
.
fprintf(stderr, "%d,%f\n", rgbValues->green, (float)rgbValues->green);
source to share
Expanding on @ AraK's answer , you cast once on float
and then printf
interpret that bit pattern as int
in a format specifier string. This does exactly what you say to do :)
If you want to use only float
- do the following:
// format specifier is %d for int, %f for float
// show the cast value of rgbValues->green as well as its "real" value
fprintf(stderr, "%d,%f\n", rgbValues->green, (float)rgbValues->green);
Edit - wording based on comments
source to share