位域

基本类型 / 数字 / 整型

//冒号后的数字是位域的宽度(以位计)
struct Date {
    unsigned day   : 5;  //0..31
    unsigned month : 4;  //0..15
    unsigned year  : 12; //0..4095
};

struct Date date = {.day = 30, .month = 9, .year = 2026};
//date is 30.9.2026

//这些位域共用一个 unsigned,而不是三个
size_t size = sizeof(struct Date);
//size is 4

//放不下的值只保留低位
struct Date wrong = date;
unsigned month = 17;
wrong.month = month;
//wrong.month 为 1(17 是 10001,四位只保留 0001)

//位域没有地址:&date.day 是错误的;
//各位在内存中的顺序取决于编译器

printf("date is %u.%u.%u\n", date.day, date.month, date.year);
printf("size is %zu\n", size);
printf("wrong.month is %u\n", wrong.month);