c 位域学习

c 位域学习

前言

在定义结构体的时候,有时候可能只需要一个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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值