Simvik

Parse an unsigned number

Convert a decimal string to uint16t, rejecting anything invalid. A medium embedded C problem (Arrays and strings), run and graded in the browser.

medium · Arrays and strings · parsing · validation · overflow

Convert the decimal string s to a uint16_t.

The string must consist of one or more digits and nothing else: no sign, no spaces, no trailing characters. The value must be at most 65535. On success store the value in *out and return true. Otherwise return false and leave *out unchanged.

Starter code

bool parse_u16(const char *s, uint16_t *out) {
  // Digits only, at least one, value <= 65535.
  return false;
}

Example tests

Valid number

uint16_t v = 9;
bool ok = parse_u16("1234", &v);
printf("%d %u\n", ok, v);

Expected output:

1 1234

Trailing garbage

uint16_t v = 9;
bool ok = parse_u16("12a", &v);
printf("%d %u\n", ok, v);

Expected output:

0 9

Learn it first

  • Arrays and strings · Decay, bounds, safe copying, and parsing and formatting without the heap.

More Arrays and strings problems