c 语言中的位域

假设你的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.

整数的类型,决定位域的值是怎么解释,这个类型可以是intsignedint ,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.

位域中位的宽度,这个宽度必须小于或者等于指定类型的位宽;

这种指定位宽的做法就是位域,当然一个位域不仅仅能保存一个位,例如,如果你需要一个变量需要存储07,这是,你可以定义一个位域,这个位域有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
原文出处: 点击打开链接
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值