[comp.lang.c] casting to float without converting to float?

roy@phri.UUCP (Roy Smith) (01/09/88)

[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