Hi,
I would like to convert a single precision hexadecimal number to
floating point. The following program seems to work fine..
But I do not want to use scanf. I already have a 32 bit hexadecimal
number and would like to convert it into float. Can anyone tell me how
to do it?
int main()
{
float theFloat;
{
scanf("%f", &theFloat);
This reads a group of characters in the usual form for
a floating-point constant, converts them to a `float' value,
and stores the result in `theFloat'. Or perhaps it fails
because there's no more input, or because the input stream
provided "blue Hawaii" instead of something that looks like
a number, or for some other reason. You should check the
value returned by the scanf() function to see whether it has
actually converted and stored a number.
printf("0x%08X, %f\n", *(int *)&theFloat, theFloat);
The output may or may not be meaningful; on some machines
it might not work at all (for example, you might get SIGBUS
or some other kind of trap). You are trying to pretend that
the representation of the floating-point value `theFloat' can
also be understood as an `int', and this may or may not be so.
Many machines will give some kind of result, but different
machines are likely to give different results, and the C language
itself doesn't guarantee any result at all.
C does provide one special guarantee for a restricted form
of type-punning: it is permitted to access the individual bytes
of any object's representation through a pointer of the type
`unsigned char*'. For example, you could do
unsigned char *p = (unsigned char*)&theFloat;
printf ("0x");
while (p < (unsigned char*)(&theFloat + 1))
printf ("%02X", *p++);
printf (", %f\n", theFloat);
to print the individual bytes one at a time. (Even this isn't
perfect, by the way: a byte can have more than eight bits and
hence more than two hexadecimal digits. Machines where this is
the case are rare, but do exist.) This loop is guaranteed to
produce output and not to trap or anything like that, but the
output you get from machine A may not match that from machine B.
However, you actually asked about going the other way: from
a stream of hexadecimal digits to a floating-point value. You
could use a loop to convert the bytes one at a time (the inverse
of what's shown above), but the byte stream that produces 42.0
on machine A might produce -273.16 on machine B, or a NaN, or
even a signalling NaN that traps when you try to use it. There
is no One True Representation of a floating-point value as a
hexadecimal string -- so what, exactly, are you trying to do?