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:
7An upper-case letter
printf("%d\n", digit_value('A'));Expected output:
10Learn it first
- Binary and hexadecimal · Bits, bytes, hex digits and negative numbers, the way hardware actually stores values.
More Binary and hexadecimal problems
- Value of a bit position · Compute how much each bit of a binary number is worth.
- Largest value in n bits · Work out the range of an unsigned number from its width.
- Count the ones · Read off the binary digits of a number one at a time.
- How many bits? · Find the width needed to store a value.
- Split a byte into hex digits · Find the two hex digits of a byte with division and remainder.
- Read a byte as signed · Interpret the same eight bits as a negative number.