1

我正在尝试访问位字段:

下面是运行良好并给出预期结果的代码,但会引发我在下面提到的编译器警告。

#include <stdio.h>
#include <stdint.h>


struct status_type_one{
unsigned delta_cts : 1;// lsb
unsigned delta_dsr : 1;
unsigned tr_edge : 1 ;
unsigned delta_rec : 1;
unsigned cts : 1;
unsigned dsr : 1;
unsigned ring : 1;
unsigned rec_line : 1;// msb
} status_one;

struct status_type_two {
unsigned : 4; // lsb 4 bits
unsigned cts : 1; //bit 5
unsigned dsr : 1; // bit 6
} status_two;



int main(void)
{
  status_one.delta_cts=1;
  status_one.delta_dsr=0;
  status_one.tr_edge=1;
  status_one.delta_rec=0;
  status_one.cts=1;
  status_one.dsr=0;
  status_one.ring=1;
  status_one.rec_line=1;

  printf("The value of status_one is %x\n",status_one);  // warning here

  status_two.cts=1;
  status_two.dsr=1;

  printf("The value of status_one is %d\n",status_two);  // warning here



    return 0;
    }

但我收到以下警告:

$ gcc -Wall Bit_Fields.c -o Bit_Fields
Bit_Fields.c: In function `main':
Bit_Fields.c:35: warning: unsigned int format, status_type_one arg (arg 2)
Bit_Fields.c:35: warning: unsigned int format, status_type_one arg (arg 2)
Bit_Fields.c:40: warning: int format, status_type_two arg (arg 2)
Bit_Fields.c:40: warning: int format, status_type_two arg (arg 2)

输出正确,如下图所示

$ ./Bit_Fields
The value of status_one is d5
The value of status_one is 48

任何人都可以告诉,警告是关于什么以及如何解决它?

谢谢

4

1 回答 1

3

解决这个问题的典型方法是使用整数类型的联合值,例如:

union status_type_one
{
   struct status_type_one{
       unsigned delta_cts : 1;// lsb
       unsigned delta_dsr : 1;
       unsigned tr_edge : 1 ;
       unsigned delta_rec : 1;
       unsigned cts : 1;
       unsigned dsr : 1;
       unsigned ring : 1;
       unsigned rec_line : 1;// msb
   } bits;
   unsigned whole[1];       // Size should match the total bits size.
} status_one;

现在,您的其他代码必须更改:

status_one.bits.delta_cts=1;
status_one.bits.delta_dsr=0;
status_one.bits.tr_edge=1;
... etc ...

和打印:

printf("The value of status_one is %x\n",status_one.whole[0]);

[显然,如果整个结构体不止一项,则需要循环或将多个值传递给 printf]

您正在做的事情可能看起来很有效,但是您实际上不应该将 STRUCT 传递给 printf 函数,并且如果您使用超过一个机器字的数据,或者在 64 -位机等

于 2013-01-10T09:41:18.867 回答