Just dropped by, and saw this...
Code: Select all
// read a Hex value and return the decimal equivalent
uint8_t parseHex(char c) {
if (c < '0')
return 0;
if (c <= '9')
return c - '0';
if (c < 'A')
return 0;
if (c <= 'F')
return (c - 'A')+10;
}
I suggest either to remove all the 'return 0;' for speed or adding a return 0 at the bottom for reliability.
Personally, I prefer returning a negative number (which is more than 8 bit), in case there's an error in parsing the hex number; eg. something like this:
Code: Select all
int16_t parseHex(char c)
{
if(c >= '0' && c <= '9')
{
return(c - '0');
}
else if(c >= 'A' && c <= 'F')
{
return(c + 10 - 'A')
}
else if(c >= 'a' && c <= 'f')
{
return(c + 10 - 'a');
}
return(-1);
}
This is just a basic piece of code.
Since we're dealing with a single digit here, you may even choose to change back the result to a uint8_t, and then return any value above 16, to indicate an error. I've added the lowercase check, in case you'd like to use this routine for something else as well.
Ofcourse, most of the time, these errors will not happen, and it might not mean anything when dealing with a microcontroller (and a hobby project), but if some of you should happen to work with code that controls devices with automatic navigation, it could become a reason for accidents, which you'd probably like to avoid.
For completeness...
Code: Select all
uint8_t hexDigit(uint8_t value)
{
char *hex = "0123456789ABCDEF";
return((uint8_t) hex[value & 0x0f]);
}
Exercises for the reader: Put the hex digits in progmem, change the routine to a macro, to save binary space.