A common use for union is to ease breaking up a STREAM of input, in the
example below breaking an int value read into two short values.
/* tunion.c */
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
/* Usage: tunion <binfile */
int
main(int argc,char *argv[])
{
union {
unsigned ii;
struct {
short high;
short low;
} word;
} decode;
printf("sizeof(decode) = %d\n",sizeof(decode));
printf("sizeof(decode.ii) = %d\n",sizeof(decode.ii));
printf("sizeof(decode.word) = %d\n",sizeof(decode.word));
printf("sizeof(decode.word.high) =
%d\n",sizeof(decode.word.high));
printf("sizeof(decode.word.low) =
%d\n",sizeof(decode.word.low));
/* Reads 0x01020304 from stdin */
read(0,&decode.ii,sizeof(decode.ii));
printf("high word = %04hx\n",decode.word.high);
printf("low word = %04hx\n",decode.word.low);
/* Reads 0x04030201 from stdin */
read(0,&decode.ii,sizeof(decode.ii));
printf("high word = %04hx\n",decode.word.high);
printf("low word = %04hx\n",decode.word.low);
}
Redirecting a file containing eight bytes, below, you can use the union
variable decode to get direct access to the two 16 bit words of the int
value read.
binfile contains: "^A^B^C^D^D^C^B^A" (quotes not in file)
CJ