在C语言中,占空间最小的类型是char类型,占8bit。某些情况下,因空间有限,一个char类型中的不同bit要代表不同的信息,通过位移来操作起来很麻烦,容易出错,这个时候就要用到位域,简单方便
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
typedef struct test {
unsigned char a : 4; /* 0000 */
unsigned char b : 2; /* 00 */
unsigned char c : 2; /* 00 */
} test_t;
int main(int argc, char const *argv[])
{
unsigned char s = 0;
test_t t;
printf("sizeof(test_t): %lu\n", sizeof(test_t));
t.a = 0xF;
t.b = 0x3;
t.c = 0x3;
printf("t.a: %d t.b: %d t.c: %d\n", t.a, t.b, t.c);
memcpy(&s, &t, sizeof(test_t));
printf("s: %d\n", s);
return 0;
}
结构体test_t所占空间的大小为8bit。可以存储3段信息,分别占用4bit 2bit 2bit的空间