We have ATOI(), ATOL(), ATOF() but no function for converting Ascii to Hex.
The sscanf function can be used to convert a string containing hex digits (like 0x123) to an integer or other type.
Hex (base 16) is a way of displaying a number, like binary (base 2), octal (base 8), or decimal (base 10).
Or, have I completely missed what you want?
I was thinking more ease of use.
My understanding of sscanf (I have limited programming experience) is that it's most effective if you're pulling certain data from a known formatted string.
I kind of look at it like this: If you had a string like "123.456" and you wanted to convert it to a float would it be easier to use ATOF() or SSCANF() to convert the number?
The same question should apply to a Hex number in a string.
The advantage of sscanf is that there is only one function to know and use to convert any string that contains numeric data to a specific type. The disadvantage is that it is a bit larger than atof, atoi, or atol (or atoh).
Anyway, the function you are looking for isn't atoh - ascii to hex - because hex isn't a type like int, float, or long. It's more like ahtoi - ascii hex to integer.
Have a look at strtol. This is a handy function for converting binary, octal, hex and/or decimal strings to integers.
Here you go.
strtol() is the key...
/
*
* Convert a hex ascii string to a number.
*/
int
htoi(char *p)
{
/*
* Look for 'x' as second character as in '0x' format
*/
if ((p[1] == 'x') || (p[1] == 'X'))
return(strtol(&p[2], (char **)0, 16));
else
return(strtol(p, (char **)0, 16));
}
--- bill
We have ATOI(), ATOL(), ATOF() but no function for converting Ascii to Hex.
Paul said it best, but...
We have atoi(), atol(), and atof() because i, l, and f (int, long, float) are different internal formats for numbers. "hex" is NOT an "internal" format; it's an external format. So you might have "htoi" and "htol", but xtoh() doesn't make any sense...
This thread is maybe old, but for the record this is what I found included in most of the BLinkM examples for Arduino:
// a really cheap strtol(s,NULL,16)
#include <ctype.h>
uint8_t toHex(char hi, char lo)
{
uint8_t b;
hi = toupper(hi);
if( isxdigit(hi) ) {
if( hi > '9' ) hi -= 7; // software offset for A-F
hi -= 0x30; // subtract ASCII offset
b = hi<<4;
lo = toupper(lo);
if( isxdigit(lo) ) {
if( lo > '9' ) lo -= 7; // software offset for A-F
lo -= 0x30; // subtract ASCII offset
b = b + lo;
return b;
} // else error
} // else error
return 0;
}