#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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With