union2.c

/*
 * demonstrate how a union works
 *
 * this sets up something as a float and then
 * accesses it as an integer
 *
 * Matt Bishop, ECS 36A, Fall 2019
 */
#include <stdio.h>
#include <string.h>

/*
 * union to treat a variable
 * as either an integer or a float
 */
union floattoint {
	int x;			/* ... as an integer */
	float f;		/* ... as a float */
};

/*
 * floating point number to use
 */
#define FLOAT   2.456

/*
 * and now the conversion
 */
int main(void)
{
	union floattoint u;	/* u can be treated as an integer or a float */

	/*
	 * give u a float value
	 */
	u.f = FLOAT;
	
	/*
	 * now print it out as a float, a hexadecimal integer,
	 * and a decimal integer
	 */
	printf("%f 0x%x %d\n", u.f, u.x, u.x);

	/* bye! */
	return(0);
}


UC Davis sigil
Matt Bishop
Office: 2209 Watershed Sciences
Phone: +1 (530) 752-8060
Email: mabishop@ucdavis.edu
ECS 36A, Programming & Problem Solving
Version of April 2, 2024 at 12:13PM

You can get the raw source code here.

Valid HTML 4.01 Transitional Built with BBEdit Built on a Macintosh