CBFalconer <cb********@yahoo.comwrites:
my************@gmail.com wrote:
>>
I saw a line of codes in the "Fast Inverse Square Root" like this:
Float InvSqrt(float x) {
......
int i = *(int *) &x; //get bits for floating value
....
x = * (float *) &i; //convert bit back to float
If x =1, &x = 0x0013fe54 and *(int *) &x = 1065353216. Can anyone
help me why I got these numbers? If I want to do the same operation
in Fortran, how can I do it?
The code is illegal, or at least system dependent. Conversion of
float* to int and of int to float* is undefined in C.
I suggest being careful with the word "illegal". I don't think the C
standard uses that term.
The quoted code does not violate any syntax rule or constraint, so in
that sense it's legal; an implementation is not required to reject it,
or even to issue any kind of diagnostic.
Conversion between int* and float* isn't undefined, but it can result
in Bad Things Happening. Specifically (C99 6.3.2.3p7):
A pointer to an object or incomplete type may be converted to a
pointer to a different object or incomplete type. If the resulting
pointer is not correctly aligned for the pointed-to type, the
behavior is undefined. Otherwise, when converted back again,
the result shall compare equal to the original pointer. When a
pointer to an object is converted to a pointer to a character
type, the result points to the lowest addressed byte of the
object. Successive increments of the result, up to the size of
the object, yield pointers to the remaining bytes of the object.
So the above can certainly cause problems if int and float have
different alignment requirements, but it *can* work as expected on
some systems. But it's highly non-portable.
--
Keith Thompson (The_Other_Keith) <ks***@mib.org>
Looking for software development work in the San Diego area.
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"