int i = *(int*)&x;
says "take the four bytes which make up the float value x, and treat them as if they were an int." float values and int value are stored using completely different methods (e.g. int 4 and float 4.0 have completely different bit patterns)
+5
A:
James Curran
2010-08-10 19:03:39
+5
A:
int i = *(int*)&x;
doesn't convert x
to an int -- what it does is get the actual bits of the float x
, which is usually represented as a whole other 4-byte value than you'd expect.
For reference, doing this is a really bad idea unless you know exactly how float values are represented in memory.
cHao
2010-08-10 19:04:38
It's even more of a bad idea because the reinterpretation invokes undefined behavior and modern compiler writers love to just optimize it away.
Stephen Canon
2010-08-11 18:02:49
+1
A:
The number that ends up in i
is the binary value of the IEEE floating point representation of the number in x. The link explains what that looks like. This is not a common C idiom, it's a clever trick from before the SSE instructions got added to commercially available x86 processors.
Nathon
2010-08-10 19:26:50