Re: bits for floating value and converting
- From: ymuntyan@xxxxxxxxx
- Date: Tue, 27 Nov 2007 21:08:54 -0800 (PST)
On Nov 27, 7:25 pm, Keith Thompson <ks...@xxxxxxx> wrote:
CBFalconer <cbfalco...@xxxxxxxxx> writes:
myfem.analy...@xxxxxxxxx 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.
It violates aliasing rules, and not just in theory:
muntyan@munt10:/tmp$ cat file.c
#include <stdio.h>
int main (void)
{
float a = 2.;
int b = *(int*)&a;
b = ~b;
a = *(float*)&b;
printf ("%f\n", a);
return 0;
}
muntyan@munt10:/tmp$ gcc file.c # no optimizations
muntyan@munt10:/tmp$ ./a.out
-2.000000
muntyan@munt10:/tmp$ gcc file.c -O2
muntyan@munt10:/tmp$ ./a.out
0.000000
Best regards,
Yevgen
.
- References:
- bits for floating value and converting
- From: myfem . analyzer
- Re: bits for floating value and converting
- From: CBFalconer
- Re: bits for floating value and converting
- From: Keith Thompson
- bits for floating value and converting
- Prev by Date: Re: Some more questions about C
- Next by Date: Free Webhosting Absolutely free no popup, no ads, no catch
- Previous by thread: Re: bits for floating value and converting
- Next by thread: Re: bits for floating value and converting
- Index(es):
Relevant Pages
|