How does bit field alignment work?

Hi all:
I encountered this question when i participated a paper test today.So the question is the forgoing title.

Two bit field structures occupy the same amount of memory,huh.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <stdio.h>
int main(int argc,char* argv[]){
  typedef struct test1{
    char a:2;
    long b:3;
    char c:2;
    short d:1;
    long long int e:3;
}test1;
typedef struct test2{
    char a:2;
    long b:3;
    char c:2;
    short d:1;
    //long long int e:3;
}test2;
  printf("test1:%d test2:%d\n",sizeof(test1),sizeof(test2));
  return 0;
}

The result:
test1:4 test2:4

In case you dont believe it,check out this link http://codepad.org/R6MXehVj

So,how did this happen,please explain the bit field alignment in details? Is it use bit-packed alignment or is it compiler-implementation specific.

Thanks in advance!
It is entirely compiler and implementation specific:
  - whether bitfields are packed from LSB to MSB or from MSB to LSB
  - how much padding is applied to the end of the structure
  - how much padding is applied between differently-typed items (IIRC)

The integer type you give to the left is only how the bitfield is to be interpreted when unpacked (that is, when you use it). It only actually uses the number of bits you specify on the right when packed into your structure.

You'll need to review your course notes for more information.

In real life, avoid bit fields. The standard makes a mistake by providing bitfields but not specifying exactly how they are to packed. IMO, at least. That makes bit-packed fields inconvenient when working with real bytes -- and requires the programmer to resort to manual bit-packing with the bit-operators anyway.

Hope this helps.
So it is compiler and implementation specific,can you explain the result in "that" particular implementation.

Thanks for any help !
How would I do that? You've already got the answer: your compiler is free to pad the end of the structure. It looks like your compiler is padding the structure to four bytes -- a common integer size (the size of a long int).
Thanks,but in retrospect ,it is not suitable to ask question like this in a paper test. I am still wondering whether i had choosen the right answer.
Last edited on
What was the question, what was your answer? I think it's all about the bit field resulting in a size of 12Bit and the structure gaining a size of 4 chars (32 Bit) Through alignment. As said it's implementation specific - the result could have theoretically been anything.
Topic archived. No new replies allowed.