前言
在定义结构体的时候,有时候可能只需要一个bool值,但是c99标准并不存在bool
类型,但是对于每一个人物中的struct都是需要申请内存的,一个int
完全可以拆分成32个bool
例子
#include <stdio.h>
#include <stdlib.h>
struct test1_s {
unsigned int a;
unsigned int b : 1;
unsigned int c;
};
int test_weiyu1() {
struct test1_s *weitest = W_ZMALLOC(struct test1_s);
weitest->a = 1;
weitest->b = 1;
weitest->c = 1;
printf("%d", sizeof(struct test1_s));
}
int main(int argc, char *argv[])
{
test_weiyu1();
}
4 + 1 + 4 最后进行补齐,变成12
验证上面的说法
#include <stdio.h>
#include <stdlib.h>
struct test1_s {
unsigned int a;
unsigned int b : 1;
unsigned int c;
};
int test_weiyu1() {
struct test1_s *weitest = W_ZMALLOC(struct test1_s);
weitest->a = 1;
weitest->b = 8;
weitest->c = 1;
printf("%d\n", sizeof(struct test1_s));
printf("a=%d\n", weitest->a);
printf("b=%d\n", weitest->b);
printf("c=%d\n", weitest->c);
}
int main(int argc, char *argv[])
{
test_weiyu1();
}
结果为
12
a=1
b=0
c=1
剩下的可以自行尝试修改位域的范围,其实在协议的定义中,可以看到很多在一个字节内定义多个含义的方法,来最大化的减少空间的占用,来提升程序的提升效率
参考文章
https://www.runoob.com/cprogramming/c-bit-fields.html