/* * demonstrate how a union works * * this sets up something as a string 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 an * array of characters */ union chtoint { int x; /* ... as an integer */ char a[8]; /* ... as 7 characters (+ '\0') */ }; /* * the string to use * the characters are (in hex): * 30, 31, 32, 33, 34, 35, 36, 37, 0 */ char *str = "1234567"; /* * 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 chtoint u; /* u can be treated as an integer or a string */ /* * give u a string value * note overflow won't occur here */ strcpy(u.a, str); /* * now print it out as a string, a hexadecimal integer, * and a decimal integer */ printf("%s -- 0x%x or %d\n", u.a, u.x, u.x); /* * the string as bits */ prbits(u.x); /* bye! */ return(0); }