有些数据在存储时并不需要占用一个完整的字节,只需要占用一个或几个二进制位即可,比如int是4个字节,有时候我们需要的数据只需要占用1个字节,这样就多出3个字节没有用,比较占用内存,c语言提供了一种叫位域的操作,它可以使我们在定义变量时制定该变量成员的二进制位数。比如:
#include<stdio.h>
#include<windows.h>
#include<string.h>
struct
{
int bit1 : 3;
int bit2 : 5;
int bit3 : 7;
}data;
int main()
{
printf("%d\n", sizeof(data));
system("pause");
return 0;
}
成员中:后的每个数字表示该变量占用的二进制位数,所以这个结构体一共占4个字节,这样会比较节省内存。
定义位域时,各个成员的类型最好保持一致,比如都用char,或都用int,不要混合使用,这样才能达到节省内存空间的目的。
#include<stdio.h>
#include<windows.h>
#include<string.h>
struct
{
int c;
int b ;
int a ;
char z;
char f ;
float e;
}data;
int main()
{
printf("%d\n", sizeof(data));
system("pause");
return 0;
}
上面的结构体占20个字节。
#include<stdio.h>
#include<windows.h>
#include<string.h>
struct
{
int c:2;
int b :2;
int a :2;
char z:2;
char f :2;
float e;
}data;
int main()
{
printf("%d\n", sizeof(data));
system("pause");
return 0;
}
而使用位域后会占12个字节。