networking · beginner · ~15 min

Decode TCP flag byte into individual flags

Bit extraction at fixed offsets through a header byte.

Challenge

TCP's flag byte (octet 13 of the TCP header) packs eight 1-bit flags:

bit 0 (LSB): FIN
bit 1:       SYN
bit 2:       RST
bit 3:       PSH
bit 4:       ACK
bit 5:       URG
bit 6:       ECE
bit 7 (MSB): CWR

Implement:

void decode_tcp_flags(unsigned char flag_byte,
                      int *fin, int *syn, int *rst, int *psh,
                      int *ack, int *urg, int *ece, int *cwr);

Each output pointer receives 0 or 1 based on the corresponding bit. All output pointers are non-NULL in the harness.

Examples

flag_byte = 0x12  (binary 0001 0010 = ACK | SYN)
   -> syn=1, ack=1, everything else=0

flag_byte = 0x01
   -> fin=1, rest=0

Why this matters

A SYN scan, an ACK flood, and a TCP teardown all show up as specific flag patterns. Knowing how to decode the byte is the first step in any TCP-aware packet inspector — or in writing a unit test against a fixture for one.

Why this matters

Firewalls, intrusion detectors, and load balancers all inspect TCP flag bits (SYN, ACK, FIN, RST). The packed byte is the most basic example of bit extraction over a fixed schema.

Input format

One byte + eight output pointers.

Output format

Each pointer set to 0 or 1.

Constraints

No allocations; assume all output pointers are non-NULL.

Starter code

void decode_tcp_flags(unsigned char flag_byte,
                      int *fin, int *syn, int *rst, int *psh,
                      int *ack, int *urg, int *ece, int *cwr) {
    /* TODO */
}

Common mistakes

Reversing the bit ordering (some references label the MSB as bit 0). Forgetting to & 1 after the shift — leaks higher bits.

Edge cases to handle

0x00 (all zero); 0xFF (all one); typical pairs like 0x12 (SYN+ACK).

Complexity

O(1).

Background lessons

Up next

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