#include<stdio.h>
int main(){
struct value
{
int bit1:1;
int bit2:4;
int bit3:4;
}
bit ={1,2,2};
printf("%d %d %d \n",bit.bit1,bit.bit2,bit.bit3);
return 0;
}
Output : -1 2 2
Hi ,I am not able to understand structure bitfields.How the negative value is coming .
can store 00(0), 01(1), 10(-2), 11(-1) *Assuming 2s complement system for signed
can store 00(0), 01(1), 10(2), 11(3)
Bit representation of both types that can be represented is same but the interpretation is different.
You are using
:1
, so it can store 0 or -1, so the negative output. You are trying to store 1, which can not be represented byint :1
, so the output is surprising. Takeaway is, don't do that.Conclusion Almost always use
unsigned
for bitfield members. Rewrite the structure as: