In the following 2 structures,
typedef struct _a {
short a1:13 __attribute__((packed));
char a2[4] __attribute__((packed));
} a;
typedef struct _b {
short b1:10 __attribute__((packed));
short b2:10 __attribute__((packed));
short b3:12 __attribute__((packed));
} b;
In struct b
, I find that bits of b2 are packed with b1, and bits of b3 are packed with b2. It ultimately results in 4 byte value.
I was expecting the similar behaviour with struct a
but I don't see the same. First 2 bytes are occupied with a1 (unused 5 bits) and following by 4 bytes for a2.
Is this behaviour expected? Why can't I pack the char[4] along with short:13? Is there a way to achieve it?
(Too long to be a comment, so i put it as an answer)
To pack all fields together, you must replace the array with 4 fields:
typedef struct _a {
short a1:13 __attribute__((packed));
char a2_0:8 __attribute__((packed));
char a2_1:8 __attribute__((packed));
char a2_2:8 __attribute__((packed));
char a2_3:8 __attribute__((packed));
} a;