프로그래밍 언어/C, C++
[c] 공용체(Union) 사용법(feat. Embedded)
EastHoon
2020. 12. 31. 10:57
1. 공용체 특징
구조체와는 다르게 '가장 큰 자료형 크기를 기준으로' 모든 멤버가 공간을 공유한다.
2. 사용 예시(in embedded system)
typedef union
{
struct
{
uint32_t _reserved0: 1;
uint32_t SLEEPONEXIT: 1;
uint32_t SLEEPDEEP: 1;
uint32_t _reserved1: 1;
uint32_t SEVONPEND: 1;
uint32_t _reserved2: 27;
} b;
uint32_t w;
} SCR_Type;
SCR_Type SystemControlRegister;
SystemControlRegister.w = SCB->SCR;
//SystemControlRegister.b.SLEEPDEEP = 1;
SCB->SCR = 0x100; //For example
SCB->SCR = SystemControlRegister.w;
상황
SCR_Type 공용체를 이용하여 SCB->SCR 레지스터에 접근한다.
예시
SCR_Type 공용체에서 w와 struct b가 메모리 공간을 공유하므로, SystemControlRegister 변수 값을 백업하기 위해 w 멤버를 이용한다.
출처
반응형