cybersecurity · beginner · ~15 min

Build one line of an xxd-style hex dump

A reusable hex-dump primitive.

Challenge

Implement int hex_dump_line(unsigned long offset, const unsigned char *bytes, int n, char *out, int cap).

Format: OFFSET: HH HH HH HH HH HH HH HH HH HH HH HH HH HH HH HH ASCII

  • OFFSET = 8 lowercase hex digits.
  • Bytes shown in two groups of 8, separated by 2 spaces.
  • Missing bytes (n < 16) emit (3 spaces) instead of HH .
  • ASCII gutter: each byte renders as itself if printable (>= 0x20 && < 0x7f), else ..

n is the count of bytes (0..16). Returns bytes written (excluding NUL), or -1 if would not fit.

Why this matters

A hex dump is the universal byte-level debugger. Knowing how to lay one out in 16-byte rows with an ASCII gutter is a daily forensic skill.

Input format

offset + bytes + count + output + cap.

Output format

Bytes written (or -1).

Constraints

Use snprintf or hand-roll; bound everything.

Starter code

#include <stddef.h>
int hex_dump_line(unsigned long offset, const unsigned char *bytes, int n, char *out, int cap) { /* TODO */ (void)offset; (void)bytes; (void)n; (void)out; (void)cap; return -1; }

Common mistakes

Treating non-ASCII as printable. Off-by-one on the row of 16.

Edge cases to handle

n == 0 (empty row). n == 16 (full row).

Complexity

O(n).

Background lessons

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