Вопрос

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?

Это было полезно?

Решение 2

(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;

Другие советы

a2 is not a bit-field so it will never be put together with a1. The standard says

Values stored in non-bit-field objects of any other object type consist of n × CHAR_BIT bits, where n is the size of an object of that type, in bytes. The value may be copied into an object of type unsigned char [n] (e.g., by memcpy); the resulting set of bytes is called the object representation of the value.

So such a sub-object must be an addressable unit, and there is not exception possible from that rule.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top