Concept of bit field

前端 未结 4 1178
故里飘歌
故里飘歌 2021-01-03 07:50
struct A
{
 int a:2;
 int b:3;
 int c:3;
};

int main()
{
 struct A p = {2,6,1};
 printf(\"\\n%d\\n%d\\n%d\\n\",p.a,p.b,p.c);
 return 0;
}    

Outp

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-03 08:30

    I get -2 -2 1 with my C compiler. The problem is that your bit fields are too small for the numbers you are trying to store. In the first two cases, the leftmost bits are 1's, so they are interpreted as negative numbers. To fix this, either:

    1. Make your bit fields larger
    2. Declare your bit fields as unsigned ints instead of ints
    3. Cast to unsigned int before printing and use %u to print.

提交回复
热议问题