Type punning in C

Walter Bright bright at Data-IO.COM
Tue Oct 10 05:08:56 AEST 1989


In article <475 at idacrd.UUCP> desj at idacrd.UUCP (David desJardins) writes:
<   Does anyone have any ideas on how one should go about converting an
<integer to the floating-point number with the same bit pattern?

Try a union:
	union blah { int i; float f; } x;
	x.f = f;
	/* now manipulate x.i */

<   It doesn't seem that there is any equally straightforward way to
<accomplish this in C.  I don't want to involve pointers because the
<whole point is efficiency, and I expect that it will be very difficult
<for any compiler to optimize out the dereferences in something like
<      int i;
<      float x;
<      * (int *) & x = i;
<to produce a single register-to-register transfer (or not even that).

Not at all. It's a pretty much standard and trivial optimization to
convert *(int*)&x=i into MOV X,I. Feel free to use it, with the caveat
that float format is not the same from machine to machine. I've done
it many times to do special manipulations on doubles.



More information about the Comp.lang.c mailing list