Yodai said:
Hi all!
I have an int that comes with a value like 0x07fa and I have to turn it into
a float value
of 204.2 decimal to display it....
0x07FA is a valid representation of a value of
an integer type, if that integer type's size is
large enough. It might or might not be a valid
representation of a value of a floating point type.
This depends upon the floating point representation
used by your implementation. For one system, it
might mean e.g. 204.2, on others it might mean
something else entirely, or not a valid value at all.
IMO the only reasonable way to "convert" 0x07FA into
204.2 is to write e.g:
float cvt(int i)
{
return i == 0x7FA ? 204.2 : i;
} /* (returns origninal value if it was not 0x7FA) */
if I try to divide it by
10 I get bogus numbers.
If you divide it by ten, you get a value other than
what you started with. This is *not* a "conversion"
it's an arithmetic operation with a defined result.
You'll get a *single* valid quotient, not "bogus
numbers".
If you divide the integer value 0x07FA by ten, the result
will be 0xCC. (Fractional portion of the quotient
is discarded -- this is how 'integer division' works
in C.) Again, the representation of this value is a
valid integer value, but might or might not be a valid
floating point value. If it is a valid floating point
value for more than one platform, the actual represented
value might or might not be the same for all those platforms.
I presume I have to make it decimal before
calculating,
All values in a C program are represented with
binary. In C source code, integer values can be
expressed in decimal (or octal, or hexadecimal.)
Floating point values are expressed in decimal.
but I am not sure about it. Any light upon this simple (or it
seems to me so, at least) begginner problem?
/* Here's what I believe you're looking for: */
int i = 0x7FA;
float f = i / 10.0f;
printf("%f\n", f); /* prints 204.2 */
Unless using the 'bit pattern' for some special
purpose (which imo only makes sense with an integer type),
one should almost always express values in source code in
decimal, and pay attention to conversion rules while performing arithmetic.
In the above example, the expression:
f = i / 10.0f;
Causes the type 'int' object 'i' to be converted
to a floating point type, then floating point division
is performed, yielding a floating point result of 204.2
had I written:
f = i / 10;
No conversion would be performed before the division,
which would be done as integer division, yielding
a result of 204, which is converted to floating point
value of 204.0
The expression 10 is an integer constant.
10.0f and 10.0 are floating point constants.
The former has type 'float', the latter, type
'double'.
-Mike