Manjunathan
Manjunathan

Reputation: 25

Can you explain how int values are stored in bitfields in C, please?

#include <stdio.h>

struct marks{
    int p:4;
    int c:3;
    unsigned int m:2;
};

void main()
{
    struct marks s = {-15, 5, 3};
    printf("%d %d %d\n", s.p, s.c, s.m);
}

Output:

1 -3 3

Why is the first value printed as 1 and the second value is printed as -3?

Upvotes: 3

Views: 114

Answers (2)

dbush
dbush

Reputation: 225477

The value 5 in binary is 101. Because the field in question is a 3 bit signed, and the most significant bit is set, the value is negative. In two's complement representation, it is -3.

Upvotes: 0

Jim Rhodes
Jim Rhodes

Reputation: 5095

For p, you are allocating 4 bits. Therefore your valid range of values for p is 1000B - 0111B or -8 to 7. The fewest number of bits needed for -15 is 5 which in binary would be 10001B. Since you only allocated 4 bits, the sign bit is lost and you are left with 1.

For c, your are allocating 3 bits which has a valid range of 100B - 011B or -4 to 3. Since 5 is 101B and outside the valid range, it is displayed as -3.

Upvotes: 5

Related Questions