Simvik

Parse a hex byte

Convert two hexadecimal characters to a value. An easy embedded C problem (Arrays and strings), run and graded in the browser.

easy · Arrays and strings · parsing · hex

Intel HEX records, MAC addresses and many debug protocols carry bytes as two hexadecimal characters.

Return the value (0 to 255) of the first two characters of s, accepting both upper and lower case. Return -1 if either character is not a hex digit, including when the string is shorter than two characters.

Starter code

int hex_to_byte(const char *s) {
  // "7F" -> 127, "a0" -> 160, "G1" -> -1
  return -1;
}

Example tests

Upper case

printf("%d\n", hex_to_byte("7F"));

Expected output:

127

Lower case

printf("%d\n", hex_to_byte("a0"));

Expected output:

160

Learn it first

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

More Arrays and strings problems