我从 Is it possible to insert three numbers into 2 bytes variable? 的一个很好的答案中看到了一段代码
For example, I want to store date which contain days, months, years.
- days ->
31
, months ->12
, years ->99
.I want to store
31
,12
,99
in one variable, and will use shift operators<<
and>>
to manipulate it.
//Quoted: the C code from that answer
union mydate_struct {
struct {
uint16_t day : 5; // 0 - 31
uint16_t month : 4; // 0 - 12
uint16_t year : 7; // 0 - 127
};
uint16_t date_field;
};
现在,我的问题是为什么要用 union 包装结构?除了关注内存还有什么特别的好处?
附言:我知道一些典型的用法来确保 union 的内存大小。
因为如果只是使用 struct
,使用起来似乎更直接简单:
typedef struct {
uint16_t day : 5; // 0 - 31
uint16_t month : 4; // 0 - 12
uint16_t year : 7; // 0 - 127
} mydate_struct;
更新1:
关于在此处包装 union 的好处的一些结论:
- 能同时初始化年月日
The advantage of using the union is that give union my_datestruct u; you can write u.date_field = 0x3456; and initialize the year, month and day fields simultaneously. It is defined by the implementation what that does, and different implementations could define it differently. There's a modest chance that the year will be 0x56, the month 0x08, and the day 0x06 (aka 86-08-06 — century not clearly defined); there's also a modest chance that the year will be 0x1A, the month 0x02, and the day 0x1A (aka 26-02-26 — century still not clearly defined). People have forgotten Y2K already. ----comment of @Jonathan Leffler
- 您可以一次读取/写入整个数字。(----@StenSoft 的评论)
最佳答案
union
意味着其中的每个部分都将使用相同的内存,因此您可以使用第一部分或第二部分(它们可以是完全不同的东西)。在您的情况下,它要么是整个结构,要么是 uint16_t date_field
。
在链接问题的上下文中,作者打算使用它来将具有两个字节大小的结构转换为两个字节的整数,反之亦然。为结构分配一些东西并从同一内存中读取 int 值。但这在 C++ 中是不允许的,并且可能行不通(多种原因......)。无法在使用的部件之间任意切换。
关于c - 为什么要用 union 包装结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31127755/