Unpredictable response in the bitfield

Could you explain to me why the output of this code is 12 (1100b)

and how sizeof (bit1) is 4 bytes ???

#include <stdio.h> #include <stdlib.h> struct bitfield { unsigned a:5; unsigned c:5; unsigned b:6; }; void main() { char *p; struct bitfield bit1={1,3,3}; //a=00001 ,c=00011 ,b=000011 p=&bit1; // p get the address of bit1 p++; // incriment the address of p in 1 printf("%d\n",*p); printf("%d\n",sizeof(bit1)); } 
+2
source share
2 answers

You declared your bitfields as unsigned . On most modern systems, this is a 32-bit integer. (unsigned short - 16, char 8, long 64, etc.) So, you are declaring a 32-bit bitfield container. The size of each individual argument of the bit field is determined by the integer after the name of the bit field, but the size of the container into which they are packed is a multiple of the specified data type ... usually the smallest multiple of the total number of bits fits - although word boundaries and other things will play it.

I am surprised that everything else works in general. Besides casting issues in the pointer, printf prints the first 8 bits of the entire field ... one char. This will not break on the bit fields themselves, but on the byte / char boundary. Depending on whether your system is large or finite, it will be either the MSB or the LSB of the entire field.

+2
source

Pointer p contains the address of the structure variable bit1 .

I believe that your system has a small endian addressing, because of which the variable b is placed at the location indicated by the pointer p and * p, prints the contents of the first two bytes of bit1 .

In your case b=3 (000011)

But two bytes contain

 00000000 00001100 (12) ------ ^ | Value of b 

To better understand this,

change the value of b to 5 (000101) as follows:

 struct bitfield bit1={1,1,5}; 

Then your output will be 20 because

 00000000 00010100 (20) ------ ^ | Value of b 

The bitfield structure packs a , c and b into an unsigned integer. The size of unsigned integers is 4 bytes .

+1
source

All Articles