c / expert
Snippet
Structured Binary Header Packing using Explicit Bit-Field Specifiers
Illustrates bit-level data packing via C structure bit-fields combined with compiler packing attributes to model fixed binary protocol format structures directly without manual bitmasking.
snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <stdio.h>#include <stdint.h>typedef struct __attribute__((__packed__)) {uint8_t version : 4;uint8_t ihl : 4;uint8_t tos : 8;uint16_t length : 16;uint16_t id : 16;uint16_t flags : 3;uint16_t fragment : 13;} PacketHeader;void parse_header(const PacketHeader* hdr) {uint8_t ver = hdr->version;uint16_t frag_offset = hdr->fragment;(void)ver; (void)frag_offset;}
Breakdown
1
__attribute__((__packed__))
Disables structural memory alignment padding bytes between adjacent bitfield byte boundaries.
2
uint8_t version : 4;
Restricts the struct member allocation width explicitly to 4 bits of storage space.
3
uint16_t fragment : 13;
Allocates a non-byte-aligned 13-bit width field inside a 16-bit wide storage container.