假设你的c应用程序中在一个结构体status包含一些 true/false变量例如:
struct { unsigned int widthValidated; unsigned int heightValidated; } status;
这个结构提需要8字节的内存空间,但是实际上我们需要在每个变量中存储0或者1,在这种情况下,c语言提供了一个更好的方式来利用内存空间,如果你在结构体这些变量,然后你可以定义每个变量的宽度,这个变量的宽度是用来告诉c编译器需要使用的字节数,例如,上面的例子可以改写为:
struct { unsigned int widthValidated : 1; unsigned int heightValidated : 1; } status;
现在,上面的结构体将需要4个字节的内存空间,但是仅仅只有2个字节用来存储变量的值。如果你使用完了32个变量(每个变量的宽度只有一个位onebit),所以这个结构体将使用4个字节,但是一旦你有33个变量,编译器将分配写一个内存块,所以一共将使用8个字节,我们测试下面的例子来理解上面的例子:
#include <stdio.h> #include <string.h> /* define simple structure */ struct { unsigned int widthValidated; unsigned int heightValidated; } status1; /* define a structure with bit fields */ struct { unsigned int widthValidated : 1; unsigned int heightValidated : 1; } status2; int main( ) { printf( "Memory size occupied by status1 : %d\n", sizeof(status1)); printf( "Memory size occupied by status2 : %d\n", sizeof(status2)); return 0; }
当编译和执行上面的代码,结果如下:
Memory size occupied by status1 : 8 Memory size occupied by status2 : 4
在一个结构体里面声明一个位域的语法是:
在一个结构体里面声明一个位域的语法是:
struct { type [member_name] : width ; };
Elements | Description |
---|---|
type | An integer type that determines how the bit-field's value isinterpreted. The type may be int, signed int, unsigned int. 整数的类型,决定位域的值是怎么解释,这个类型可以是int,signedint ,unsigned int |
member_name | The name of the bit-field. 位域的名称 |
width | The number of bits in the bit-field. The width must be lessthan or equal to the bit width of the specified type. 位域中位的宽度,这个宽度必须小于或者等于指定类型的位宽; |
这种指定位宽的做法就是位域,当然一个位域不仅仅能保存一个位,例如,如果你需要一个变量需要存储0到7,这是,你可以定义一个位域,这个位域有3个位宽,例如:
struct { unsigned int age : 3; } Age;
#include <stdio.h> #include <string.h> struct { unsigned int age : 3; } Age; int main( ) { Age.age = 4; printf( "Sizeof( Age ) : %d\n", sizeof(Age) ); printf( "Age.age : %d\n", Age.age ); Age.age = 7;
printf( "Age.age : %d\n", Age.age ); Age.age = 8; printf( "Age.age : %d\n", Age.age ); return 0; }
编译执行,得到如下结构:
Sizeof( Age ) : 4 Age.age : 4 Age.age : 7 Age.age : 0原文出处: 点击打开链接