-
Notifications
You must be signed in to change notification settings - Fork 0
Bitfield vs Packed
MarekBykowski edited this page May 26, 2026
·
1 revision
// PACKED — removes padding between fields
struct __attribute__((packed)) pkt {
uint8_t magic; // offset 0
uint32_t seq; // offset 1 — no padding inserted
}; // sizeof = 5
// BITFIELD — controls field size in bits
struct uart_reg {
uint32_t enable : 1; // 1 bit, values 0–1
uint32_t mode : 3; // 3 bits, values 0–7
uint32_t baud : 4; // 4 bits, values 0–15
uint32_t reserved : 24; // 24 bits — 1+3+4+24 = 32 total
}; // sizeof = 4packed |
bitfield |
|
|---|---|---|
| Controls | padding between fields | field size in bits |
| Min. field | 1 byte | 1 bit |
&field |
works | ✗ compile error |
| Bit order | N/A | unspecified by standard |
| Linux kernel | network protocols | IP header only |
⚠️ Mixing container types (uint8_t+uint32_t) in bitfields → unexpected padding between groups. Use one type throughout.