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?
&x is the memory address of the variable x. The exact address you
get may vary from invocation to invocation. That you got
0x0013fe54 was more or less chance. The exact value that you got
has no particular significance.
*(int *) &x means to reinterpret the memory location x
as an int. This operation was not certain to succeed: you -might-
have been running on a system in which int requires stricter
alignment than float. And in C in general, the length of a float
is not necessarily the same as the length of an int -- it is not
uncommon for the two to be the same length, but sometimes int
is shorter than float, and sometimes int is longer than float.
It looks like it happened that on your compiler, the two are
the same length.
The exact value you got from the reinterpretation, 1065353216,
is equivilent to hex 0x3f800000 . Through experience, I recognize
that as the IEEE 754 single precision floating point
representation of 1.0 . You can find out more about IEEE 754 at
http://en.wikipedia.org/wiki/IEEE_floating-point_standard
If I want to do the same operation in
Fortran, how can I do it?
That's a Fortran question rather than a C question. The answer
is going to depend upon which Fortran standard you are using,
and possibly upon system extensions. Historically, you could
often play tricks like that using the %VAL and %REF FORTRAN
extensions; I see a hint that this might have become VAL()
in later versions, but you'd need to check that in your documentation
and in comp.lang.fortran
You might find the most straight-forward way in Fortran to get at the
bit representations is to push the value into a common block declared
one way, and then call a function that declares the common block
a different way (e.g., with an INTEGER*4 variable in that location.)