例如,我想存储包含日、月、年的日期。
- 天->
31
, 月 ->12
, 年 ->99
.
我要存储31
, 12
, 99
在一个变量中,并将使用移位运算符 <<
和 >>
操纵它。
我尝试做的事情:
short date = 0;
date = 31; // day
date << 5;
date = 12; // month
date << 7;
date = 99; // year
printf("date: %d\n", date >> 15); // print the first value
但结果是0
.
我不知道这个想法本身是否可行。
最佳答案
是的,这是可能的。我会使用适当的 union
来屏蔽值区域:
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;
};
这使您的年份范围从 0 到 127。您的决定,如果这足以满足您的实际用例。
关于c++ - 是否可以将三个数字插入到 2 个字节的变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31126714/