Convert String to HEX on arduino platform

14,736

I don't have arduino installed in my PC right now, so let's hope the following works:

char nibble2c(char c)
{
   if ((c>='0') && (c<='9'))
      return c-'0' ;
   if ((c>='A') && (c<='F'))
      return c+10-'A' ;
   if ((c>='a') && (c<='a'))
      return c+10-'a' ;
   return -1 ;
}

char hex2c(char c1, char c2)
{
   if(nibble2c(c2) >= 0)
     return nibble2c(c1)*16+nibble2c(c2) ;
   return nibble2c(c1) ;
}

String hex2str(char *data)
{
   String result = "" ;
   for (int i=0 ; nibble2c(data[i])>=0 ; i++)
   {
      result += hex2c(data[i],data[i+1]) ;
      if(nibble2c(data[i+1])>=0)
        i++ ;
   }
   return result;
}
Share:
14,736

Related videos on Youtube

ndarkness
Author by

ndarkness

Updated on June 04, 2022

Comments

  • ndarkness
    ndarkness almost 2 years

    I am doing a small parser that should convert a string into an Hexadecimal value,I am using arduino as platform but I am getting stack with it.

    My string is data = "5449" where each element is an char, so I would like to translate it to a HEX value like dataHex = 0x54 0x59, and finally those values should be translate to ASCII as dataAscii= TI

    How can I do this?

    I was thinking of splitting it into an char array with dataCharArray = 54 49 and later converting those values to the chars T and I, but I am not sure whether or not that is the best way.

    Thanks in advance,

    regards!

  • ndarkness
    ndarkness about 8 years
    thanks it is working, I have added some missing closing parenthesis and a result, but for the rest seems to work fine, thanks!
  • ndarkness
    ndarkness about 8 years
    on e quick question, if I want the data just in HEX, as dataHex = 0x54 0x59 that is given by the function hex2c right?
  • Alphonsos_Pangas
    Alphonsos_Pangas about 8 years
    hex2c converts two hex characters to the character they encode. For example, "35" to "5", "3B" to ";", "6D" to "m". Have a look at an ASCII table and I hope this will be made clear.