linux-sysprog · intermediate · ~15 min
Format bytes safely with snprintf into a bounded buffer.
Format one line of a hex dump: the bytes as two-digit hex, then the same bytes as printable ASCII.
Implement int hexdump_line(const unsigned char *data, size_t n, char *out, size_t out_sz) that renders up to 16 bytes as a single hex-dump line into out.
data, n: the bytes to render (n is at most 16).out, out_sz: destination buffer and its size in bytes.Writes "<hex> |<ascii>|" into out: each byte as lowercase %02x followed by a space, then a |, then one ASCII char per byte (the byte itself if printable, otherwise .), then a closing |. Returns 0 on success, or -1 if out_sz is too small to hold the full line.
bytes = { 'h', 'i', 0x01, '!' }
hexdump_line(bytes, 4, out, 128) -> 0, out = "68 69 01 21 |hi.!|"
hexdump_line(bytes, 4, small, 8) -> -1 (buffer too small)
0x01) shows as . in the ASCII column.-1.A byte buffer data of length n (n <= 16), plus an output buffer out of size out_sz.
Writes '
Hex is lowercase %02x with a trailing space per byte. Use snprintf and check every return value.
#include <stdio.h>
#include <ctype.h>
#include <stddef.h>
int hexdump_line(const unsigned char *data, size_t n, char *out, size_t out_sz) {
/* TODO */
return -1;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.