Xref: utzoo comp.unix.wizards:6167 comp.lang.c:6433 Path: utzoo!mnetor!uunet!husc6!cmcl2!phri!roy From: roy@phri.UUCP (Roy Smith) Newsgroups: comp.unix.wizards,comp.lang.c Subject: Re: casting to float without converting to float? Message-ID: <3103@phri.UUCP> Date: 8 Jan 88 16:56:35 GMT References: <11171@brl-adm.ARPA> Reply-To: roy@phri.UUCP (Roy Smith) Followup-To: comp.lang.c Organization: Public Health Research Inst. (NY, NY) Lines: 40 Summary: Use unions [This really doesn't belong on unix.wizards; I've moved it to comp.lang.c] In article <11171@brl-adm.ARPA> weiser.pa@Xerox.COM writes: > I have a value which I happen to know has the proper bits to represent > a floating point number (either 32 or 64). However, it is of type int. > I would now like to tell the C compiler to treat this thing as a float. I think what you want to do is declare a union which has both int and float elements and use whever you prefer whenever you want. For example, the following program (compiled on a Sun-3, under SunOS-3.2) does what you want. Lint doesn't even complain (except about ignoring the value printf returns). Before you do this, however, be aware that this is not exactly what I would call portable code (although, as long as sizeof(int) >= sizeof(float), I don't see why it shouldn't work anywhere). Better than assembler in-lines, at any rate. main () { union {int i; float f;} x1, x2; int i; float f1, f2; f1 = 3.0; x1.f = f1; i = x1.i; /* i now has bit pattern for 3.0e0 */ printf ("%d\n", i); x2.i = i; f2 = x2.f; printf ("%f\n", f2); } alanine% cc test.c alanine% a.out 1077936128 3.000000 -- Roy Smith, {allegra,cmcl2,philabs}!phri!roy System Administrator, Public Health Research Institute 455 First Avenue, New York, NY 10016