Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

#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?

like image 323
Manjunathan Avatar asked Dec 31 '25 23:12

Manjunathan


1 Answers

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.

like image 105
Jim Rhodes Avatar answered Jan 02 '26 15:01

Jim Rhodes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!