位域声明的异常语法

Unusual syntax for bitfield declaration

我遇到了以前从未见过的位域语法。

       struct msg_hdr0{
                        uint8_t a  : 1,
                        b         : 1,
                        e         : 4,
                        f         : 2;                                                                                                                                                                       
               };

     int main(void)
     {
     struct msg_hdr0 hdr;

     bzero((void *)&hdr, sizeof(hdr));
     hdr.b = 1;

     printf("hdr = 0x%X\n", *(uint32_t *)&hdr);

     return 0;
     }

这在 linux 和 gcc 编译器上运行良好。 谁能建议我在哪里可以找到这方面的任何文档。 这是 GCC 扩展吗?

常见的位域语法是:

    struct box_props
   {
 unsigned int opaque       : 1;
 unsigned int fill_color   : 3;
 unsigned int              : 4; // fill to 8 bits
 unsigned int show_border  : 1;
 unsigned int border_color : 3;
 unsigned int border_style : 2;
 unsigned int              : 2; // fill to 16 bits
};

标准 C99 部分 $6.7.2.1 表示为,

struct-declarator-list:
     struct-declarator
     struct-declarator-list , struct-declarator

struct-declarator:
     declarator
     declarator_opt : constant-expression

您可以使用 , 声明结构位字段成员,

   struct msg_hdr0 {
     uint8_t a : 1, b : 1, e : 4, f : 2;
   };

对于您的位域如何使用的问题,以下代码可能会有所帮助。位字段在 C 语言中是标准的,当不需要整个 int 的大小来存储值并且特定数量的位足以保存值时使用,这样做可以节省内存,如下所示。另一个答案中已经有一个 link 关于为什么不使用位字段但是为了理解目的是这样的。

#include <stdio.h>
struct a
{
    unsigned int a;
    unsigned int b;
};
struct b
{
    unsigned int a : 2; /* unsigned int a:2, */
                        /*              b:3;  */
    unsigned int b : 3;
};
int main(void) {
    struct b p;
    p.a = 3; /* This member can hold just 2 bits */
    p.b = 7;/* This member can hold just 3 bits */
    printf("%d\n",sizeof(struct a)); /* Size of struct is 8 bytes */
    printf("%d\n",sizeof(struct b)); /* size of struct is 4 bytes using bit fields*/
    printf("%d\n",p.a);
    printf("%d\n",p.b);
    return 0;
}

在函数中,您可以在单个语句或多个语句中声明变量列表。

void myFunction(void)
{
    // Declare several variables (of teh same type) in a single statement
    int a, b, c;
    // Declare some more, each in their own statement
    int x;
    int y;
    int z;
}

同样,结构中的位字段。

struct myStruct
{
    // Declare several bitfields in a single statement
    int a : 1, b : 3, c : 4;
    // Declare some more, each in their own statement
    int x : 1;
    int y : 3;
    int z : 4;
}