位字段?
? ? ?- ?限定結構體某個變量使用固定的二進制位
節約內存,例如嵌入式物聯網設備開發
一般情況下,
struct date{
unsigned int day;
unsigned int month;
unsigned int year;
};
這個結構體需要12個字節的空間,
但是day 取值范圍在0~31, 5個二進制位就可以了
month 取值是 1~12, ?4個二進制位就可以了
year取值 0000~9999, 14個二進制位就可以了
如何對結構體所占內存進行壓縮空間
struct date{
? ? unsigned int day : 5; ?//限定這個變量使用5個二進制位
? ? unsigned int month : 4; //限定這個變量使用4個二進制位
? ?unsigned int year : 14; //限定這個變量使用14個二進制位
};
測試用例:
void main(){
? struct date date1, *pdate;
? date1.day = 31;
? date1.month = 9;
? date1.year = 2014;
? pdate = (struct date * )malloc(sizeof(struct date));
? printf("%d-%d-%d", pdate->year, pdate->month;pdate->day);
//struct 結構是4字節對齊的
//輸出4,表示4個字節,而不是12個字節,大大節約了內存
?printf("the size of date is : %d", sizeof(struct date));
? return 0;
}
使用位字段的注意事項
1.結構體限定了位數的變量一定不能越界,越界會溢出,只保留低位的符合數量限定的位數
2. 如果2個字符, 限定位字段相加小于8位,會合并填充一個字節,通過位操作操作位字段, 不會應用字節對齊
3.結構體的對齊效應,對應4個字節,雖然為了字節對齊,有很多空白字段,但是任然會溢出,空白的位無法使用
4. 可以定義無名的位, 沒有意義,且不能使用 , 例如 // unsigned char : 3;
5.位字段成員不可以大于存儲單元的長度, 例如 //unsigned char ch3 : 10; //一個char最大為8位
6.位字段限定值取值必須大于0?
7.使用位字段限定了的結構體變量的成員,不能獲取其內存地址,
8, 沒有初始化的結構體,不能獲取其成員變量的地址