Concept of bit field

六眼飞鱼酱① 提交于 2019-11-30 15:50:31

问题


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;
}    

Output is: -2,-2,1

What would be output of above code in C complier and in C++ complier? And Why?


回答1:


Your system seems to using 2's complement. A 2-bit bit-field holding 2 would be 10 in binary which is -2 in 2's complement system. Likewise 110(6) is -2 for a 3-bit representation in 2's complement. And 1 is plain 1

Also read about signed bit-fields here




回答2:


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.



回答3:


You get those answers for the same reason that this program:

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

int main(void)
{
    int32_t a = 4294967294;
    printf("%d\n", a);
    return 0;
}

Has output -2. Initializing a signed variable with a number too large to fit causes it to be interpreted differently. From the spec:

Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.




回答4:


Now Lets see what exactly is happening. Lets start with the given code:

struct A
{
 int a:3;
};
int main()
{
 struct A p = {5};
 printf("%d",p.a);
}

within 3 bits the values would be 101(5) since sign bit of this 3 bit set is 1 thus negative value. Thus we need to find 2's compliment of 101 which would be 011(3). Thus by applying above logic we would output as -3. Similarly others could be proved.

e.g. for 1001(9) we shall take 3 bit values because of a:3. thus it would be 001(1). Since here sign bit is not set i.e. 1 so no need to use 2's complement. Straight forward answer would be 1. Similarly others could be done.



来源:https://stackoverflow.com/questions/10320731/concept-of-bit-field

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