how the output came 2 -3 8 -1

0 votes
asked Jan 7 by afjal
#
include <stdio.h>

int main(void)
{
    struct bitfields {
        int bits_1 :2;
        int bits_2 :4;
        int bits_3 :4;
        int bits_4 :3;
    } bit = {2, 3, 8, 7};
    
    printf("%d %d %d %d", bit.bits_1,bit.bits_2,bit.bits_3,bit.bits_4);

    
}

1 Answer

0 votes
answered Jan 10 by CuNi

To begin with, the output is -2 3 -8 -1 for me.
Second:
int bits_1 :2;
int bits_2 :4;
int bits_3 :4;
int bits_4 :3;

The : is the important part. You tell your Bitfield to only use 2, 4, 4 and then 3 bits.
If we look at it as bits.
You say your bits_1 only uses 2 Bits.
Then you assign the value of 2 to it.
2 = 10 but if you only use 2 Bits, your MSB is the sign bit.
So by saying bits_1 = 2 you actually do is bits_1 = 10xb whichs says Sign Bit = 1, so it's a negative number and Bit 0 = 0. So you get -2. Same explenation for the other cases.

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...