arduinoarduino-ide

Convert String to HEX on arduino platform


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!


Solution

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