union 关键字

⚠️ 待完善
本笔记尚未添加内容。


基本概念

union(联合体)是一种特殊的数据类型,所有成员共享同一块内存空间。

基本用法

1
2
3
4
5
6
7
8
9
10
11
12
13
typedef union {
uint32_t value;
struct {
uint8_t byte0;
uint8_t byte1;
uint8_t byte2;
uint8_t byte3;
} bytes;
} register_value_u;

register_value_u reg;
reg.value = 0x12345678;
reg.bytes.byte0; // 访问单个字节

典型应用

  • 内存复用
  • 字节序转换
  • 协议解析