networking · intermediate · ~15 min

Parse a chunk size

Convert a hex chunk-size line to a number.

Challenge

Parse the hex size line that prefixes each chunk in HTTP chunked transfer encoding.

Task

Implement long parse_chunk_size(const char *hex) that returns the numeric value of a hexadecimal chunk-size string.

Input

  • hex: a string containing the chunk size in hexadecimal (e.g. "1a0").

Output

Return the parsed value as a long. Return -1 if the string has no hex digits.

Example

parse_chunk_size("ff")   ->  255
parse_chunk_size("0")    ->  0
parse_chunk_size("1a0")  ->  416
parse_chunk_size("xyz")  ->  -1   (no hex digits)

Input format

hex: a string holding the chunk size in hexadecimal.

Output format

The parsed value as a long, or -1 if there are no hex digits.

Constraints

Parse base-16; detect 'no digits' (e.g. via the strtol end pointer) and return -1.

Starter code

#include <stdlib.h>
#include <ctype.h>

long parse_chunk_size(const char *hex) {
    /* TODO */
    return -1;
}

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