Convert ASCII Hex String to inidivual bytes

Hello,

I have a char[] filled with HEX values. I want to split up the char [] and display the indivual bytes. How would I do that?

For example, I have a char [] filled with "68656D6D6F". I want to be able to Serial.print->68,65,6D,6D & DF or the ASCII equivalent h,e,l,l,o.

Thanks,

-ren

Sounds like you need the undocumented atoi function

http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1261777488

Here’s a bit of code that may be of use:

/* interpret the ascii digits in[0] and in[1] as hex
 * notation and convert to an integer 0..255.
 */
int hex8(char *in)
{
   uint8_t c, h;

   c = in[0];

   if (c <= '9' && c >= '0') {  c -= '0'; }
   else if (c <= 'f' && c >= 'a') { c -= ('a' - 0x0a); }
   else if (c <= 'F' && c >= 'A') { c -= ('A' - 0x0a); }
   else return(-1);

   h = c;

   c = in[1];

   if (c <= '9' && c >= '0') {  c -= '0'; }
   else if (c <= 'f' && c >= 'a') { c -= ('a' - 0x0a); }
   else if (c <= 'F' && c >= 'A') { c -= ('A' - 0x0a); }
   else return(-1);

   return ( h<<4 | c);
}

Thanks for the replies! Thanks for the code gardner, it works great!

Maybe Im missing something, but the C function strol() does the same thing.

For example:

String instring = "68656D6D6F";

char firstByte[2]; 

instring.substring(0,2).toCharArray(firstByte, 3); //slice the string

long int firstChar = strtol(firstByte, NULL, 16); //convert slice to integer

And crossroads, i'm pretty sure atoi() wouldn't work because it doesn't allow you to specify a base for the input string, and assumes it is decimal.

bilbo:
Maybe Im missing something, but the C function strol() does the same thing.

Thanks for that - I had forgotten (never learned?) about the base parameter - it makes it much easier to recommend.

Here’s a version using chars:

char inStr[]="68656C6C6F";
//...later on...
char tmp[]="12", c='x'; // two char tmp - third is zeroed out already
int i=0, len=strlen(inStr), n=0;
for (i=0;i<len;i+=2)
{
  tmp[0]=inStr[i];
  tmp[1]=inStr[i+1];
  // tmp now has two char hex value
  n=strtol(tmp,NULL,16); // n has numeric value
  c=(char)n;  // c has character value
}