[임베디드 C] 구조체 & Union (2)

정재훈·2022년 4월 4일
0

임베디드 C언어

목록 보기
7/11
post-thumbnail

중첩 구조체

구조체 내부에 구조체를 만들 수 있습니다.

#include <stdio.h>

struct Node
{
	int a;

	struct  // 구조체 이름이 따로 필요하지 않아 생략
	{
		int b1;
		int b2;
	}b;

	int c;
};

int main()
{

	struct Node v = {0};

	v.a = 20;
	v.b.b1 = 50;
	v.b.b2 = 30;
	v.c = 10;

	return 0;
}

출력

구조체 선택적 초기화

#include <stdio.h>

struct Node
{
	int a;

	struct
	{
		int b1;
		int b2;
	}b;

	int c;
};

int main()
{
	// .[변수명]을 통해 초기화 가능
	struct Node v = {.a = 10, 
    				.b = {.b1 = 150, .b2 = 250},
    				.c = 30};
	//struct Node v = {10,150,250,30};
	

	return 0;
}

구조체와 Union 활용

1

#include <stdio.h>

typedef struct KFC
{
	union  // 5
	{
		int b1; // 5
		int b2; // 5
	}b;

	int c; // 7
}go;

int main()
{
	go shoot = {{5} , 7};

	return 0;
}

2

#include <stdio.h>

typedef union Node
{
	int a;

	struct
	{
		int b1;
		int b2;
	}b;

	int c;
}node;

int main()
{
	node v = {0};
	
	v.a = 20;  // a = 20; b.b1 = 20; b.b2 = 0; c = 20;
	v.b.b1 = 50; // a = 50; b.b1 = 50; b.b2 = 0; c = 50;
	v.b.b2 = 30; // a = 50; b.b1 = 50; b.b2 = 30; c = 50;
	v.c = 10; // a = 10; b.b1 = 10; b.b2 = 30; c = 10;

	return 0;
}

3

#include <stdio.h>
#include <stdint.h>

typedef union UNI
{
	struct // 0xCDAB
	{
		uint8_t a; // 0xAB
		uint8_t b; // 0xCD
	}d1;

	struct // 0xCDAB
	{
		uint8_t c; // 0xAB
		uint8_t d; // 0xCD
	}d2;
}go;

int main()
{
	go shoot = {0xAB , 0xCD};

	return 0;
}

4 (중요!)

#include <stdio.h>
#include <stdint.h>

typedef union UNI
{
	struct // 0x0a09
	{
    	// 내부구조로 반대로 저장된다.
		uint8_t a;  // 0x09 
		uint8_t b; // 0x0a
	}d1;

	uint16_t c; // 0x0a09 : 리틀엔디안 방식이므로 다음과 같이 저장된다.
}go;

int main()
{
	go shoot = {9 , 10};

	return 0;
}

5

#include <stdio.h>
#include <stdint.h>

typedef union UNI
{
	union // 0XABCD
	{
		struct  // 0XABCD
		{
			uint8_t da; // 0xCD
			uint8_t db; // 0xAB
		}dd;

		uint16_t dtotal; // 0XABCD
	};

	uint16_t gv; // 0xABCD
}go;

int main()
{
	go shoot = {.gv = 0xABCD};

	return 0;
}

6

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

int main()
{

	uint8_t target[11] = {0x12, 0x12, 0x12, 0x12, 0x12, 0xAB, 0xCD, 0x98, 0x76};

	union _Data_
	{
		uint8_t receiveData[11]; 
		// 0x76, 0x98, 0xCD, 0xAB, 0x12, 0x12, 0x12, 0x12, 0x12 순으로 저장되는데
		// 리틀엔디안 방식이므로 0x12, 0x12, 0x12, 0x12, 0x12, 0xAB, 0xCD, 0x98, 0x76 저장된다.

		struct // 0x76, 0x98, 0xCD, 0xAB, 0x12, 0x12, 0x12, 0x12, 0x12
		{
			// 쪼개짐
			uint8_t head[5]; // 0x12, 0x12, 0x12, 0x12, 0x12
			uint8_t body[4]; // 0xAB, 0xCD, 0x98, 0x76
			uint8_t tail[2]; // 받는게 없음
		}msg;
	}dm;

	memcpy(&dm, target, 11); // dm에 target을 7길이만큼 복사


	// Head 출력
	printf("Head = ");
	for(int i=0; i<5; i++)
	{
		printf("%02X", dm.msg.head[i]);
	}
	printf("\n");

	// Body 출력
	printf("Body = ");
	for(int i=0; i<4; i++)
	{
		printf("%02X", dm.msg.body[i]);
	}
	printf("\n");


	// Tail 출력
	printf("Tail = ");
	for(int i=0; i<2; i++)
	{
		printf("%02X", dm.msg.tail[i]);
	}
	printf("\n");

	return 0;
}

profile
여러 방향으로 접근하는 개발자

0개의 댓글