First of all, I think this is a good reason to not use signed values in bitfields. There are lots of applications where non-negative values used in bitfields are really handy, but this confusion makes signed values less appealing to use.
But to answer your question. You asked
when we extract 4 bits of twos complement pattern then it is 11 then why ans is -5 |
When you extract 4 bits of -5, you have 1011, not 11. I think that's where your misunderstanding is.
When converting from a smaller signed int value to a larger signed int value (for instance short to long), the most significant bit is replicated into the extra bits of the lager value. So, going from -5 (8-bits) to -5 (16 bits) is:
1 2
|
1111 1011
1111 1111 1111 1011
|
In your case, in order to print X.a as an integer (presumably 16-bit), the computer is making the following conversion:
1 2
|
1011
1111 1111 1111 1011
|
Because the upper bit of the 4-bit integer is 1, it gets replicated to the rest of the integer.