使用位域时,C enum作为结构中的类型

时间:2013-05-02 15:52:56

标签: c bit-fields

我的理解是位字段声明符的类型应该是某种int类型。实际上,这是C99标准中的一行

  

“比特字段的类型应为_Bool的合格或不合格版本,签名> int,unsigned int或其他一些实现定义类型。”

但是,我今天遇到了一些代码,它显示了一个枚举类型,就像这样。

typedef enum
{
    a = 0,
    b = 1
}ENUM;

typedef struct
{
    ENUM id : 8;
}STRUCT;

没有评论或文档,很难说出意图。任何人都可以提供一些见解吗?

1 个答案:

答案 0 :(得分:4)

ab都属于int类型,signed int。它的长度为 32位,表示4字节。

但是枚举ENUM并不需要那么多。

0000000000000000000000000000000 equals a
0000000000000000000000000000001 equals b

因此,创建者认为ENUM短于intbitfield长度为 8位,最小长度为1字节。

00000000 or 00000001

他可以从头开始采用char类型,长度为1 Byte。

在某些编译器上,您可以激活一个功能以确保枚举可以小于int。使用GCC的选项--short-enums,使其使用仍然适合所有值的最小类型。


以下是如何使用位域保存内存的示例。 您会看到someBits结构小于twoInts结构。

#include "stdio.h"

struct oneInt {
  int x;
};

struct twoInts {
  int x;
  int y;
};

struct someBits {
  int x:2; // 2 Bits
  int y:6; // 6 Bits
};


int main (int argc, char** argv) {
  printf("type int = %lu Bytes\n", sizeof(int));
  printf("oneInt = %lu Bytes\n", sizeof(struct oneInt));
  printf("twoInts = %lu Bytes\n", sizeof(struct twoInts));
  printf("someBits = %lu Bytes\n", sizeof(struct someBits));
  return 0;
}

输出:

type int = 4 Bytes
oneInt = 4 Bytes
twoInts = 8 Bytes
someBits = 4 Bytes