Simvik

Value of a hex digit

Convert a hexadecimal character into the number it stands for. An easy embedded C problem (Binary and hexadecimal), run and graded in the browser.

easy · Binary and hexadecimal · hexadecimal · characters

Hexadecimal has sixteen digits. After 0 to 9 come A to F, standing for 10 to 15. Lower-case letters mean the same.

A char is a small number, the code of a character. Return the value (0 to 15) of the hex digit c, or -1 if c is not a hex digit.

Starter code

int digit_value(char c) {
  if (c >= '0' && c <= '9') {
    return c - '0';
  }
  return -1;
}

Example tests

A decimal digit

printf("%d\n", digit_value('7'));

Expected output:

7

An upper-case letter

printf("%d\n", digit_value('A'));

Expected output:

10

Learn it first

  • Binary and hexadecimal · Bits, bytes, hex digits and negative numbers, the way hardware actually stores values.

More Binary and hexadecimal problems