Go Down

Topic: How about ATOH()? Ascii to Hex (Read 7050 times) previous topic - next topic

wayneft

We have ATOI(), ATOL(), ATOF() but no function for converting Ascii to Hex.
I2C GPS Shield

Checkout my Open Source GPS Tracker on Kickstarter

PaulS

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?

wayneft

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.

I2C GPS Shield

Checkout my Open Source GPS Tracker on Kickstarter

PaulS

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.

BenF

Have a look at strtol. This is a handy function for converting binary, octal, hex and/or decimal strings to integers.

bperrybap

Here you go.
strtol() is the key...

/
Code: [Select]
*
* 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

westfw

Quote
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...

@vizzino

This thread is maybe old, but for the record this is what I found included in most of the BLinkM examples for Arduino:




Code: [Select]

// 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;
}



Go Up