linux-sysprog · intermediate · ~15 min

Print a hex dump line

Format bytes safely with snprintf into a bounded buffer.

Challenge

Format one line of a hex dump: the bytes as two-digit hex, then the same bytes as printable ASCII.

Task

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.

Input

  • data, n: the bytes to render (n is at most 16).
  • out, out_sz: destination buffer and its size in bytes.

Output

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.

Example

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)

Edge cases

  • A non-printable byte (e.g. 0x01) shows as . in the ASCII column.
  • If the buffer cannot hold the whole line, return -1.

Input format

A byte buffer data of length n (n <= 16), plus an output buffer out of size out_sz.

Output format

Writes ' ||' into out. Non-printable bytes show as '.'. Returns 0 on success, -1 if out is too small.

Constraints

Hex is lowercase %02x with a trailing space per byte. Use snprintf and check every return value.

Starter code

#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.