0

I am working on a project where I first need to build up the payload as a string then later on convert it to byte when sending the payload. I am having issues with conversion.

Reson why payload build-up is in string is due to the way it generates each single string, "02", "12", "31", "03" and "36" are the result after diffrent methods of calculations.

String lockHexString[5];  
lockHexString[0] = "02"; 
lockHexString[1] = "12"; 
lockHexString[2] = "31"; 
lockHexString[3] = "03"; 
lockHexString[4] = "36"

Now when I have lockHexString, I need convert the lockHexString to byteArray, so It looks like

byte lockByte[5] = {0x02, 0x12, 0x31, 0x03, 0x36};
kaylum
  • 13,833
  • 2
  • 22
  • 31
Nabil Akhlaque
  • 192
  • 1
  • 8
  • Does this answer your question? [Convert string of hex to char array c++](https://stackoverflow.com/questions/47204749/convert-string-of-hex-to-char-array-c) – kaylum Jun 26 '21 at 23:36
  • @kaylum Those answers are useless on the system having 2kB of RAM. No std at all. – 0___________ Jun 26 '21 at 23:40
  • @0___________ I probably should have linked directly to the answer that that post is duplicated to. It has an answer without `std`. https://stackoverflow.com/questions/17261798/converting-a-hex-string-to-a-byte-array – kaylum Jun 26 '21 at 23:42
  • no sorry, that method takes too much memory, as I only have 2kb. – Nabil Akhlaque Jun 27 '21 at 21:30
  • Maybe you shouldn't use the String to create the payload to begin with. If you use `char*` strings, then `atoi()` would be a simple solution. or Maybe if you could store your string as decString instead of hexString, then at least you could easily convert it to a byte with `(uint8_t) String.toInt()`. – hcheung Jun 28 '21 at 01:14

1 Answers1

1

If they are always 2 chars I would not use heavy standard functions on Arduino. Simple:

unsigned getdigit(const char ch)
{
    switch(ch)
    {
        case '0' ... '9':
          return ch - '0';
        case 'a' ... 'f':
          return ch - 'a';
        case 'A' ... 'F':
          return ch - 'A';
        default:
          return 0;
    }
}
unsigned char convHEX(const char *str)
{
    return getdigit(str[0]) * 16 + getdigit(str[1]);
}
0___________
  • 60,014
  • 4
  • 34
  • 74