networking · beginner · ~15 min
Bit extraction at fixed offsets through a header byte.
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.
flag_byte = 0x12 (binary 0001 0010 = ACK | SYN)
-> syn=1, ack=1, everything else=0
flag_byte = 0x01
-> fin=1, rest=0
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.
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.
One byte + eight output pointers.
Each pointer set to 0 or 1.
No allocations; assume all output pointers are non-NULL.
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 */
}
Reversing the bit ordering (some references label the MSB as bit 0). Forgetting to & 1 after the shift — leaks higher bits.
0x00 (all zero); 0xFF (all one); typical pairs like 0x12 (SYN+ACK).
O(1).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.