Simvik

Parse a byte, report why it failed

Return a status code and write the result only when parsing succeeded. An easy embedded C problem (Error handling), run and graded in the browser.

easy · Error handling · error-handling · status-codes · parsing

Write parse_u8(s, out), which reads an unsigned decimal number from the text s.

It returns one of:

StatusWhen
ERR_OKall characters are digits and the value is 0 to 255
ERR_EMPTYthe string is empty
ERR_NOT_DIGITany character is not 0 to 9
ERR_RANGEthe number is above 255

*out is written only on ERR_OK; on any error it keeps its previous value. Check characters in order, so "12x" is ERR_NOT_DIGIT.

Starter code

status_t parse_u8(const char *s, uint8_t *out) {
  *out = (uint8_t)atoi(s);
  return ERR_OK;
}

Example tests

A valid number

show("200");

Expected output:

"200": status=0 value=200

Empty and not a number

show("");
show("12x");

Expected output:

"": status=1 value=99
"12x": status=2 value=99

Learn it first

More Error handling problems