home *** CD-ROM | disk | FTP | other *** search
/ Jason Aller Floppy Collection / 98.img / LCNOW2.ZIP / EXAMPLES / UNION_2.C < prev    next >
C/C++ Source or Header  |  1988-08-02  |  1KB  |  54 lines

  1. /*
  2.  * U N I O N _ 2
  3.  *
  4.  * Use a union to access the same areas of memory
  5.  * as either bytes or words at different times.
  6.  */
  7.  
  8. /*
  9.  * Data structure definitions.
  10.  */
  11. struct bytes {
  12.     unsigned char low;
  13.     unsigned char high;
  14. };
  15.  
  16. union word {
  17.     unsigned short word;
  18.     struct bytes byte;
  19. };
  20.  
  21.  
  22. int
  23. main(void)
  24. {
  25.     union word data;
  26.     unsigned short temp;
  27.  
  28.     /*
  29.      * Save a number in memory as a word and print it
  30.      * in both decimal and hexadecimal formats.
  31.      */
  32.     data.word = 1000;
  33.     printf("Word = %u (%04X hex)\n", data.word, data.word);
  34.  
  35.     /*
  36.      * Print out the values of the low and high bytes
  37.      * of the word independently.
  38.      */
  39.     printf("Low byte = %u (%02X hex)\n",
  40.         data.byte.low, data.byte.low);
  41.     printf("High byte = %u (%02X hex)\n",
  42.         data.byte.high, data.byte.high);
  43.  
  44.     /*
  45.      * Print out the value of the word calculated from
  46.      * the high and low bytes of the memory word.  The
  47.      * calculation is equivalent to (256 * high) + low.
  48.      */
  49.     temp = (data.byte.high << 8) | data.byte.low;
  50.     printf("Calculated data word = %u (%04X hex)\n", temp, temp);
  51.  
  52.     return (0);
  53. }
  54.