1 분 소요

#include
#ifdef _____what______

union 에 대한 고찰

un 공용체의 경우 int형을 쓰고 싶으면 a멤버를 참조하고 short형을 쓰고 싶으면
b멤버를 참조하면 된다. 기록할 때는 int형으로 기록하고 읽을 때는 상하위 워드를
나누어 short형으로 읽을 수도 있으며 반대로 상하위 워드를 각각 따로 변경한 후
읽을 때는 32비트의 int형으로 읽는 것도 가능하다. 좀 더 개념적으로 이해하기
쉬운 예를 들어 보도록 하자.

union tag_ip {

unsigned long addr;

unsigned char sub[4];

};

이 공용체는 인터넷 주소인 IP값을 저장하는데 IP는 32비트의 부호없는 정수로 되어
있지만 표기할 때는 210.238.128.136과 같이 한 바이트씩 10진수로 쓰는 것이 일반적
이다. 표기를 위해서 값을 읽을 때는 sub 배열을 읽는 것이 편리하고 실제 통신을
위해 주소값을 전달할 때는 32비트의 addr멤버를 읽는 것이 효율적이다

#endif

typedef union _test{
char t_char;
int t_int;
double t_double;
int t_array[10];
}test_union, *test_union_p;

int main(int argc, char *argv[])
{
test_union t_union;
t_union.t_char=’a’;
t_union.t_int=10;
t_union.t_double=999.99;
t_union.t_array[0]=0;

printf(“size of t_union %d
“,sizeof(t_union));

printf(“address of t_union.t_char = %d size of t_union.t_char %d

,&t_union.t_char, sizeof(t_union.t_char));

printf(“address of t_union.t_int = %d size of t_union.t_int %d

,&t_union.t_int , sizeof(t_union.t_int));

printf(“address of t_union.t_double = %d size of t_union.t_double %d

,&t_union.t_double , sizeof(t_union.t_double));

printf(“address of t_union.t_array[0] = %d size of t_union.t_array %d

,&t_union.t_array[0] , sizeof(t_union.t_array));

printf(“%d”, (int)t_union.t_char);
printf(“%d”, t_union.t_array);

return 0;
}

#ifdef __conclusion___

결국 마지막에 입력한 값이 저장된다고 생각하면 맞는것 같다.
그리고 내가 이것을 사용하여 데이터 처리를 할때.
32비트프로세서로 16비트 통신을 하게되면 상당히 유용할것으로 보인다.

#endif
\