The input from the PC is a character, i.e. an ASCII-value. To understand how this is saved, have a look at the ASCII-table. The numbers '0' to '9' are represented by the ASCII-codes 0x30
to 0x39
. The capital letters 'A' to 'Z' are represented by 0x41
to 0x5A
, and the small letters 'a' to 'z' by 0x61
to 0x7A
.
You could of course use a function like sscanf
, as suggested by @JohnO'M. Such functions (printf
, scanf
, ...) have many features but thus require a lot of power and memory[Citation needed], which we often don't want to spend on a microcontroller. A simple alternative would be to distinguish the 3 possible cases (0-9 or A-F or a-f) and subtract the correct number from the ASCII code to get to the result:
if( (s >= 0x30) && (s <= 0x39)) { // 0-9
x = s - 0x30;
}
else {
if( (s >= 0x41) && (s <= 0x46)) { // A-F
x = s - 0x37;
}
else {
if( (s >= 0x61) && (s <= 0x66)) { // a-f
x = s - 0x57;
}
else { // wrong input
x = 0xFF;
}
}
}