I am newbie to C. I googled alot regarding the output of below code.But not much of help.
Here is the code:
struct str
{
int i: 1;
int j: 2;
int k: 3;
int l: 4;
};
struct str s;
s.i = 1;
s.j = 2;
s.k = 5;
s.l = 10;
printf(" i: %d \n j: %d \n k: %d \n l: %d \n", s.i, s.j, s.k, s.l);
Output:
i: -1
j: -2
k: -3
l: -6
Can anyone explain why the outputs are so ? Thanks.
Because your fields are not unsigned
, thus they are signed.
If you have a signed field, its most significant bit dindicates negativeness. This implies that there is always one more negative value than positive - at least, in the implementation which you use, which seems to use two's complement numbers for negative.
If you put a 10
in a bit field of 4 bits, you have 1010
, which is negative (-6
).
If you put a 5
in a bit field of 3 bits, you have 101
, which is negative (-3
).
If you put a 2
in a bit field of 2 bits, you have 10
, which is negative (-2
).
If you put a 1
in a bit field of 1 bits, you have 1
, which is negative (-1
).
With
struct str
{
unsigned int i: 1;
unsigned int j: 2;
unsigned int k: 3;
unsigned int l: 4;
};
you should be able to achieve what you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With