data-structures · beginner · ~15 min
Define and manipulate C struct bitfields with deterministic bit serialization.
C struct bitfields (unsigned int field : bits) allow packing multiple small fields into compact bit widths, directly mirroring hardware control blocks and network headers.
Given the 8-bit packet flag bitfield:
typedef struct {
unsigned int fin : 1;
unsigned int syn : 1;
unsigned int rst : 1;
unsigned int psh : 1;
unsigned int ack : 1;
unsigned int urg : 1;
unsigned int reserved : 2;
} TcpFlags;
Implement packing and decoding:
uint8_t pack_tcp_flags(TcpFlags flags);
TcpFlags unpack_tcp_flags(uint8_t raw);
pack_tcp_flags: packs the bitfield into a single uint8_t:finsynrstpshackurgreservedunpack_tcp_flags: extracts the 8 bits from raw into the matching bitfield members of TcpFlags and returns the struct.TcpFlags f = { .syn = 1, .ack = 1 };
uint8_t b = pack_tcp_flags(f); // bit 1 (0x02) | bit 4 (0x10) = 0x12
TcpFlags out = unpack_tcp_flags(b); // out.syn == 1, out.ack == 1
TcpFlags bitfield or uint8_t byte.
Returns packed uint8_t or unpacked TcpFlags.
Zero dynamic allocations. Strict bit mapping.
#include <stdint.h>
typedef struct {
unsigned int fin : 1;
unsigned int syn : 1;
unsigned int rst : 1;
unsigned int psh : 1;
unsigned int ack : 1;
unsigned int urg : 1;
unsigned int reserved : 2;
} TcpFlags;
uint8_t pack_tcp_flags(TcpFlags flags) {
(void)flags;
return 0;
}
TcpFlags unpack_tcp_flags(uint8_t raw) {
(void)raw;
TcpFlags f = {0};
return f;
}
Assuming bitfield memory layout is portable across endian architectures without explicit mask packing.
All flags 0 produces 0; all flags 1 produces 0xFF; reserved bits preserved.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.