位域
位域,即将一个字节中的二进制位划分为不同的几个区域,并说明每个区域的位数
位域的声明
struct name{
//[]代表可选
int [name] : width;
unsigned int [name] : width;
signed int [name] : width;
};
//对位域的操作和结构体类似
//位域变量.位域名 or 位域变量->位域名
补充说明
-
类型只能为上面的三种类型
-
当这个域为无名时,只用来填充或调整位置,不能使用
-
位域的宽度不能超过他所依附的数据类型的长度
-
如果一个字节中剩余的空间不够下一个位域时,会从下一个自己开始存储
例子说明:
example:
struct potion{
int isMale : 1;
int is_student : 1;
int is_teacher :1;
}people;
int main(){
people.isMale=0;
people.is_student=0;
people.is_teacher=1;
printf("%d\n",people.isMale);
people.is_student=3;//超出数据范围
printf("%d",people.student);
return 0;
}