May 25

Converting HEX as a String to actual HEX values

Last night I spent quite a bit of time figuring out how to go from a string containing “7E00101700000000000000000013380244320520” which is an XBee API packet to actually writing those hex values to the XBee. The packet has been assembled with PHP and a database backing it.

That data was echo’ed onto an HTML page which an Arduino (with an Ethernet connection) parsed. Basically what I did was reading the string one character at a time, here are bits of the code:

byte incFrame[100];
byte c = 0x0;
 
c = client.read();
incFrame[stringPos] = c;
stringPos++;

As you can see I stored the data in a byte array. But when you want to write the data to the Serial line, you need to perform some operations to make it actually work. A long story short, here’s the solution, I’m sure other people have spent messing around with this problem in the past and will in the future.

byte getVal(char c)
{
   if(c >= '0' && c <= '9')
     return (byte)(c - '0');
   else
     return (byte)(c-'A'+10)
}

This is needed to properly convert the ASCII value to the hex value of each character. Next we put together 2 characters as is done with HEX notation and send the data:

  for(int i = 0; i < stringPos; i+=2)
  {
    byte sendb = getVal(incFrame[i+1]) + (getVal(incFrame[i]) << 4);
    Serial.write(sendb);
  }

And there you have it, a string containing hex values as ascii is properly converted into actual HEX. There are other ways to do it but this is how I did it.