cybersecurity · intermediate · ~15 min

Parse a hex byte

Validate fixed-width hex input.

Challenge

Parse exactly two hex digits into a byte value, rejecting anything that is not precisely two valid hex characters — the fixed-width discipline binary protocols need.

Task

Implement int parse_hex_byte(const char *s, int *out) that parses the first two characters of s as hex digits into a value 0..255. Return 1 and write the value to *out on success; return 0 if s is not exactly two hex digits.

Input

  • s: a NUL-terminated string the grader provides.
  • out: where the parsed byte value is written on success.

Output

Returns 1 on success (with *out in 0..255), 0 otherwise.

Example

parse_hex_byte("ff", &out)   ->   1, out = 255
parse_hex_byte("1a", &out)   ->   1, out = 26
parse_hex_byte("f", &out)    ->   0   (too short)
parse_hex_byte("zz", &out)   ->   0   (not hex)

Edge cases

  • Fewer than two characters: return 0.
  • More than two characters (a third character present): return 0.
  • Non-hex characters: return 0. Both upper- and lower-case hex are accepted.

Input format

A NUL-terminated string s and an out pointer.

Output format

1 with *out (0..255) if s is exactly two hex digits; otherwise 0.

Constraints

Require exactly two hex digits; accept upper- and lower-case.

Starter code

int parse_hex_byte(const char *s, int *out) {
    /* TODO */
    return 0;
}

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