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. 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
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.
One unsigned char flag_byte and eight output pointers (all non-NULL in the harness).
No return value. Each of the eight int outputs is set to 0 or 1.
0x12 (0001 0010 = SYN | ACK) -> syn=1, ack=1, all others 0
0x01 -> fin=1, all others 0
0x00: every flag is 0.0xFF: every flag is 1.& 1 after shifting so higher bits do not leak in.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 unsigned char flag_byte and eight non-NULL int out-pointers (fin, syn, rst, psh, ack, urg, ece, cwr).
No return value; each output pointer is set to 0 or 1 for its bit.
No allocations; mask with & 1 after shifting. 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.