一、位域
因为在编程开发中,有时候不需要占用一根完整的字节,只需要使用几个bit或者一个bit,所以使用位域就是来节省内存空间的,并且能简单处理。
例如单片机开发中的开关只有通电和断电两种状态,用 0 和 1 表示就可以了,也就是用一个二进位。基于节省内存空间的考虑,C语言提供了一种叫做位域的数据结构。
二、位域定义
允许在一个结构体中以位为单位来指定其成员长度,这种以位为单位的结构体成员称为“位段”或者“位域”。位域只能是int、unsigned int、signed int类型。int默认是有符号整型(signed)。
位域列表的形式:
类型说明符 位域名:位域长度
(定义一个位域abc,包含3个位域成员a、b和c)
struct abc
{
unsigned int a:22;//占22位
unsigned int b:11;//占11位
unsigned int c:22;//占6位
}data;
//data为bs变量,占用两个字节
//一个位域必须存储在同一个字节中,不能跨两个字节。
//如一个字节所剩空间不够存放另一位域时,
//应从下一单元起存放该位域。也可以有意使某位域从下一单元开始。
代码验证
#include<stdio.h>
typedef unsigned char uint8_t;
typedef struct test
{//总共33个bit,4个字节不够,再开4个字节
int a: 10;
int b: 10;
int c : 13;
}test;
#define LEN(aa) sizeof(aa)
int main()
{
printf("length of test:%ld\n",LEN(test));
printf("length of uint8_t:%ld\n",LEN(uint8_t));
printf("length of int:%ld\n",LEN(int));
}
输出结果:
#include<stdio.h>
typedef unsigned char uint8_t;
typedef struct test
{
//总共30个bit,即4个字节
int a: 10;
int b: 10;
int c : 10;
}test;
#define LEN(aa) sizeof(aa)
int main()
{
printf("length of test:%ld\n",LEN(test));
printf("length of uint8_t:%ld\n",LEN(uint8_t));
printf("length of int:%ld\n",LEN(int));
}
输出结果:
在这里插入代码片