Type punning in C

David desJardins desj at idacrd.UUCP
Tue Oct 3 02:28:49 AEST 1989


   Does anyone have any ideas on how one should go about converting an
integer to the floating-point number with the same bit pattern?  One
frequently (well, occasionally) needs to do this to implement certain
bit manipulations efficiently on Cray computers and other vector
machines, and possibly on other architectures with fast floating-point
but no fast shift (?).  The best way I have found to do this in
FORTRAN is to write

      INTEGER I
      REAL X
      X = OR (I, 0).

(The Cray FORTRAN compiler optimizes out the trivial OR instruction.)

   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).

   What I think is probably necessary is to define a real function of
one integer argument, returning the same bit pattern as its input.
Ultimately I would need to get Cray to incorporate it into their C
compiler as an intrinsic function.  Does anyone have any experience
with such a thing, or a good idea of how these functions should be
named?

   -- David desJardins



More information about the Comp.lang.c mailing list