/* * 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 #include /* * 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 /* * print the bits in an integer */ void prbits(unsigned int x) { int i; /* counter in a for loop */ int bit; /* the bit */ int nbits = sizeof(unsigned int) * 8; /* how many bit in an unsigned int */ /* * loop through the (computer) word, putting out 1 bit at a time */ for(i = 0; i < nbits; i++){ /* extract ith bit */ bit = (x>>((nbits-1)-i))&01; /* print it, visibly */ printf("%c", bit+'0'); if ((i + 1) % 8 == 0) putchar(' '); } /* done -- end of line to finish it up */ putchar('\n'); } /* * 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); /* * print the bits of the word */ prbits((unsigned int) u.x); /* bye! */ return(0); }