目录

C - Bit Fields

假设您的C程序包含许多TRUE/FALSE变量,这些变量分组在一个名为status的结构中,如下所示 -

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个变量,每个变量宽度为1位,那么状态结构也将使用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 ;
};

下表描述了位字段的可变元素 -

Sr.No. 元素和描述
1

type

一种整数类型,用于确定如何解释位字段的值。 类型可以是int,signed int或unsigned int。

2

member_name

位字段的名称。

3

width

位域中的位数。 宽度必须小于或等于指定类型的位宽。

使用预定义宽度定义的变量称为bit fields 。 位字段可以容纳多个位; 例如,如果您需要一个变量来存储0到7之间的值,那么您可以定义宽度为3位的位字段,如下所示 -

struct {
   unsigned int age : 3;
} Age;

上面的结构定义指示C编译器年龄变量将仅使用3位来存储该值。 如果您尝试使用超过3位,那么它将不允许您这样做。 让我们尝试以下示例 -

#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
<上一篇.C - Unions
C - Typedef.下一篇>
↑回到顶部↑
WIKI教程 @2018