Skip to content

位域

概念

位域是一种节约内存的数据结构,需要声明域名和位数

声明

c
struct bs     
{     
int a:8;     
int b:2;     
int c:6;     
};

使用

c

#include <stdio.h>
struct Person
{
    int age:4
};

int main ()
{
    struct Person person;
    person.age = -9;
    printf("%d\n",person.age);
    

    person.age = -8;
    printf("%d\n",person.age);

    person.age = 8;
    printf("%d\n",person.age);
    

    person.age = 7;
    printf("%d\n",person.age);
    
    return 0;
}
  • 从以上案例可以看出,4位只能存储-8到7的值