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

정재훈·2022년 4월 4일
0

임베디드 C언어

목록 보기
5/11
post-thumbnail

Typedef

typedef [기존 자료형] [바뀔 자료형] : 기존 자료형을 원하는 이름으로 정의 하는 명령어

#include <stdio.h>

int main()
{
	typedef double Jeong;
	typedef float Jaehoon;

	Jeong a = 1.2222;
	Jaehoon b = 1.22222222222222;

	printf("%f %f",a,b);


	return 0;
}

구조체

기본 자료형들을 모아 새로운 자료형을 만드는 문법

#include <stdio.h>

struct ABC 
{
	int a;
	int b;
}

int main()
{
	// C++에서는 Struct 생략가능하지만, C에선 생략하면 오류 발생
	struct ABC t; 
    
   
	 // struct ABC t = {10,20}; , 값을 바로 넣을 수도 있다.
     // but 선언할 때 초기화 해주는 것은 가능하지만, t = {10,20} 와 같이 선언 외에서는 한꺼번에 초기화 불가하다.(C++ 에선 가능)
	t.a = 10;
	t.b = 20;
	
	return 0;
}

구조체 변수 만들기

struct ABC t1와 같이 따로 선언해주지 않고 struct 변수 만들 때 바로 선언 가능합니다.

#include <stdio.h>

struct ABC 
{
	int a;
	int b;
} t1, t2;   //  바로 선언해주기

int main()
{
	t1.a = 10;
	t1.b = 20;
	
	t2.a = 30;
	t2.b = 40;
	
	return 0;
}

typedef를 통해 구조체 선언 축약

#include <stdio.h>

typedef struct _ABC_    // typedef를 사용하여 복잡한 struct 변수 쉽게 만들어주기
{
	int a;
	int b;
}ABC;

int main()
{
	ABC a = { 1,2 };
	ABC b = { 3,4 };
	ABC c = { 5,6 };



	return 0;
}

구조체 예제

#include <stdio.h>

struct KFC
{
	int m1;
	char m2;
	int m3[5];
} a;

int main()
{
	struct KFC b = { 2,'B',{6,7,8,9,10} };

	a.m1 = 1;
	a.m2 = 'A';
	for (int i = 0; i < 5; i++)
	{
		a.m3[i] = i + 1;
	}


	return 0;
}

결과

Union

struct와 구조와 비슷하지만, union은 맴버끼리 값을 공유한다. struct와 마찬가지로 typedef도 사용하여 편하게 선언할 수 있다.

#include <stdio.h>

union ABC
{
	int a;
	int b;
};

int main()
{
	union ABC t = {1}; // t.a = 1;

	// t.a에 1을 넣어도 t.b에 1이 들어간다. 
	printf("%d",t.b);

	return 0;
}

바이트 단위의 파싱을 편리하게 사용할 수 있다.

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

typedef union _ABC_
{
	uint32_t a;
	uint8_t b[4];
}ACON;

int main()
{
	ACON data;

	data.a = 0x1234ABCD;

	return 0;
}

출력
Little 엔디안 방식이기 때문에 다음과 같이 출력된다.

바이트 단위 파싱

  1. Union 사용하지 않고 파싱하기
  2. Union으로 쉽게 파싱하기

1. Union 사용하지 않고 파싱하기

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

int main()
{
	uint64_t g = 0xABCD12345678CD01;
	uint8_t buf[8];

	// 리틀 엔디안 방식이기 때문에 거꾸로 출력하여
	// 사람이 보기 편한 빅 엔디안 방식으로 변수에 집어넣기
	for(int i = 7; i>=0; i--)
	{
		// 맨뒤 8bit만 뽑아내기
		buf[i] = g & 0xFF; 
		g >>= 8; // 뽑아낸 8bit 삭제
	}
	
	for(int i=0; i < 8; i++)
	{
		printf("%02X ", buf[i]);
	}

	return 0;
}

2. Union으로 쉽게 파싱하기

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

uint64_t g = 0xABCD12345678CD01;

union ABC
{
	uint64_t value;
	uint8_t buf[8];
}t1;

int main()
{
	t1.value = g; 

	// 리틀 엔디안 방식이기 때문에 거꾸로 출력하여
	// 사람이 보기 편한 빅 엔디안 방식으로 출력하기
	for(int i=7; i>=0; i--)
	{
		printf("%02X ", t1.buf[i]);
	}

	return 0;
}
profile
여러 방향으로 접근하는 개발자

0개의 댓글