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. Unpack one such byte into eight 0/1 outputs.

Bit layout:

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

Task

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) that sets each output pointer to 0 or 1 based on the matching bit of flag_byte.

Input

One unsigned char flag_byte and eight output pointers (all non-NULL in the harness).

Output

No return value. Each of the eight int outputs is set to 0 or 1.

Example

0x12  (0001 0010 = SYN | ACK)   ->   syn=1, ack=1, all others 0
0x01                            ->   fin=1, all others 0

Edge cases

  • 0x00: every flag is 0.
  • 0xFF: every flag is 1.

Rules

  • No allocations. Mask each bit with & 1 after shifting so higher bits do not leak in.

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 unsigned char flag_byte and eight non-NULL int out-pointers (fin, syn, rst, psh, ack, urg, ece, cwr).

Output format

No return value; each output pointer is set to 0 or 1 for its bit.

Constraints

No allocations; mask with & 1 after shifting. 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.