Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Details of structure in C

Tags:

c

structure

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.

like image 779
vijay Avatar asked Jan 16 '23 09:01

vijay


1 Answers

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.

like image 66
glglgl Avatar answered Jan 21 '23 18:01

glglgl