data-structures · beginner · ~15 min

Struct Bitfield Packet Header

Define and manipulate C struct bitfields with deterministic bit serialization.

Challenge

C struct bitfields (unsigned int field : bits) allow packing multiple small fields into compact bit widths, directly mirroring hardware control blocks and network headers.

Your Task

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

Rules

  1. pack_tcp_flags: packs the bitfield into a single uint8_t:
    • bit 0: fin
    • bit 1: syn
    • bit 2: rst
    • bit 3: psh
    • bit 4: ack
    • bit 5: urg
    • bits 6..7: reserved
  2. unpack_tcp_flags: extracts the 8 bits from raw into the matching bitfield members of TcpFlags and returns the struct.

Example

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

Input format

TcpFlags bitfield or uint8_t byte.

Output format

Returns packed uint8_t or unpacked TcpFlags.

Constraints

Zero dynamic allocations. Strict bit mapping.

Starter code

#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;
}

Common mistakes

Assuming bitfield memory layout is portable across endian architectures without explicit mask packing.

Edge cases to handle

All flags 0 produces 0; all flags 1 produces 0xFF; reserved bits preserved.

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.