pete <pf*****@mindspring.comwrites:
ch*******@gmail.com wrote:
>Can anyone explain the following codes?
especially the cast of pointer type.
What does it really mean. Thanks.
float f1;
unsigned long l1;
f1=4.5;
l1=*(unsigned long*)&f1;
Most likely, it means that the programmer didn't know that
ll = fl;
is the correct way to assign a value from
that float object to that unsigned long object.
I don't think that's the most likely explanation. I can easily
imagine a programmer not knowing whether a cast is necessary when
assigning a float value to an unsigned long object, but the use of
pointer casts tells me that the programmer was deliberately trying to
examine the representation of f1 as if it were of type unsigned long.
In some contexts, that might even be a reasonable thing to do, though
it's not necessarily the best way to do it, because ...
One of the possible problems with your code example
is that &f might not be aligned for a long type
which means that ((unsigned long*)&f1) might be undefined.
Here's a mostly reasonable program that incorporates the above code:
#include <stdio.h>
int main(void)
{
if (sizeof (float) == sizeof (unsigned long)) {
float f1 = 4.5;
unsigned long l1;
l1 = *(unsigned long*)&f1;
printf("f1 = %g, l1 = %lx\n", f1, l1);
if (l1 == 0x40900000) {
puts("Looks like 32-bit IEEE floating-point");
}
else {
puts("Unknown format");
}
}
else {
puts("Size mismatch");
}
return 0;
}
As you point out, alignment is a potential problem, so I'd probably
use memcpy() rather than pointer tricks. I'd probably also check more
than one value, and try harder to find a matching integer type if
unsigned long doesn't match -- but maybe I only care about some
limited set of implementations.
In fact, I have a program I use sometimes that does something similar
to the above, but I look at the floating-point object as an array of
unsigned char, whose values I compare to known values for several
floating-point values. It recognizes 32-bit, 64-bit, and 96-bit IEEE
(distinguishing between big-endian and little-endian), as well as
SPARC/HPPA and SGI 128-bit floating-point formats, plus 64-bit and
128-bit Cray floating-point. (Since I don't do exhaustive testing, a
false positive is always a remote possibility.)
--
Keith Thompson (The_Other_Keith)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"