C 位字段:了解以下程序的工作方式

C 位字段:了解以下程序的工作方式,c,bit-fields,C,Bit Fields,你能给我解释一下这个案子吗 struct REGISTRU { int bit3:4; }; struct REGISTRU bit={13}; printf("\n%d", bit.bit3); 为什么结果是-3?我创建了一个名为bit3的结构,其类型为4位长度的整数(可以存储0到15的值) 然后创建一个名为bit of type REGISTRU的变量,并将该值初始化为13 struct REGISTRU bit={13}; 最后打印出值 printf("\n%d"

你能给我解释一下这个案子吗

    struct REGISTRU
{
    int bit3:4;

};


struct REGISTRU bit={13};
printf("\n%d", bit.bit3);

为什么结果是-3?

我创建了一个名为bit3的结构,其类型为4位长度的整数(可以存储0到15的值)

然后创建一个名为bit of type REGISTRU的变量,并将该值初始化为13

struct REGISTRU bit={13};
最后打印出值

printf("\n%d", bit.bit3);

在使用位字段时,我们需要非常小心。 由于您只将变量声明为int,所以在C中,它是默认的带符号int

如果您看到二进制值13,则为1101。因此,
MSB
被作为符号值,因此得到-3。如果您希望它的值为13,请使用以下代码:

struct REGISTRU
{
   unsigned int bit3:4; 
};

void main()
{ 
  struct REGISTRU bit={13};
  printf("\n%d", bit.bit3);
}

你没有得到答案吗?@SouravGhosh你看,我知道我应该使用unsigned,但实际的问题应该在我的考试中,所以我尝试理解int的情况。用非常简单的话来说,signed=sign bit+value,所以对于4位有符号位域变量,逻辑上,(1位符号+3位值),而3位不能容纳
13
,最大值为7。因为2补码的数字13(1101二进制)大于最大正4位(有符号)整数。此最大值为7十进制==0111二进制!如果使用
unsigned int
则结果应为13!:)带符号的4位值可以使用2的补码将
-8
存储到
+7
。@Sergioformigini,我没有注意到肯定
printf(“\n%u”,bit.bit3)?是的,它会打印13。确保
struct
中的变量定义为
unsigned int
struct REGISTRU
{
   unsigned int bit3:4; 
};

void main()
{ 
  struct REGISTRU bit={13};
  printf("\n%d", bit.bit3);
}