您好,欢迎来到99网。
搜索
您的当前位置:首页c 位域学习

c 位域学习

来源:99网

前言

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

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- 99spj.com 版权所有 湘ICP备2022005869号-5

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务