c语言结构体位定义,C语言结构体位域
1、定義聲明
位段成員必須聲明為int、unsigned int或signed int類型(shortcharlong)。位域的定義和位域變量的說(shuō)明位域定義與結(jié)構(gòu)定義類似,其形式為:
struct 位域結(jié)構(gòu)名
{ 位域列表 };
其中位域列表的形式為:
類型說(shuō)明符 位域名:位域長(zhǎng)度
例如,struct packed_struct {
unsigned int f1:1;
unsigned int f2:1;
unsigned int f3:1;
unsigned int f4:1;
unsigned int type:4;
unsigned int my_int:9;
}
也可以這樣定義:struct packed_struct {
unsigned int f1:1;
unsigned int f2:1;
unsigned int f3:1;
unsigned int f4:1;
unsigned int type:4;
unsigned int my_int:9;
} pack;
使用示例如下:#include
#include
struct packed_struct {
unsigned int f1:1;
unsigned int f2:1;
unsigned int f3:1;
unsigned int f4:1;
unsigned int type:4;
unsigned int my_int:9;
} pack;
int main() {
printf("%d\n", (int) sizeof(struct packed_struct));
return 0;
}
2、位域的作用及存儲(chǔ)規(guī)則
使用位域的主要作用是壓縮存儲(chǔ),其大致規(guī)則為:
1) 如果相鄰位域字段的類型相同,且其位寬之和小于類型的sizeof大小,則后面的字段將緊鄰前一個(gè)字段存儲(chǔ),直到不能容納為止
2) 如果相鄰位域字段的類型相同,但其位寬之和大于類型的sizeof大小,則后面的字段將從新的存儲(chǔ)單元開始,其偏移量為其類型大小的整數(shù)倍;
3) 如果相鄰的位域字段的類型不同,則各編譯器的具體實(shí)現(xiàn)有差異,VC6采取不壓縮方式,Dev-C++,GCC采取壓縮方式;
4) 如果位域字段之間穿插著非位域字段,則不進(jìn)行壓縮;
5) 整個(gè)結(jié)構(gòu)體的總大小為最寬基本類型成員大小的整數(shù)倍。
總結(jié)
以上是生活随笔為你收集整理的c语言结构体位定义,C语言结构体位域的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Migw用CMD编译C语言,NOTEPA
- 下一篇: C语言算小数加减,C语言带小数加减乘除.