Please explain the output for bitfield 1

143 views Asked by At
#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 .

2

There are 2 answers

3
Mohit Jain On BEST ANSWER
int bits:2;

can store 00(0), 01(1), 10(-2), 11(-1) *Assuming 2s complement system for signed

unsigned int bits:2;

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 by int :1, so the output is surprising. Takeaway is, don't do that.

Conclusion Almost always use unsigned for bitfield members. Rewrite the structure as:

struct value
{ 
  unsigned int bit1:1;
  unsigned int bit2:4;
  unsigned int bit3:4;
};
0
Basavaraju B V On

bit1 in the structure is of type int. when you don't specify unsigned before int like unsigned int it will be treated as signedinteger! and for bit1 you have mentioned size as 1 bit, that means bit1 can have only 2 values! 0 and 1. when you assigned bit1 with 1, it will print -1 as type is int. as we know, for int variables if the MSB bit it set then it is a negative number! bit2 and bit3 are of size 4 bits, So its value can be ranged from 0 till 15 (0b1111).

To know more about bit fields, please check this link: http://www.tutorialspoint.com/cprogramming/c_bit_fields.htm