问题
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:
- Make your bit fields larger
- Declare your bit fields as unsigned ints instead of ints
- 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