Getting negative value with bit-fields

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-15 11:17:31

问题


I have a question related to bit-fields in C. Here I have such a structure:

struct Register
{
  int bit:1;
};

int main(void)
{
  struct Register bit = {1};

  printf("\nbit = %d", bit.bit);
  return 0;
}

Can you please explain me why do I get:

bit = -1


回答1:


If you're working with bitfields, you should use unsigned int. signed int is a problem for bit-fields.




回答2:


use unsigned int , it stores 0 and 1,

struct Register
{
unsigned int bit:1;
};

int main(void)
{
 struct Register bit = {1};

 printf("\nbit = %d", bit.bit);
 return 0;
}


来源:https://stackoverflow.com/questions/30614340/getting-negative-value-with-bit-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!