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};
5
  • Does this answer your question? Convert string of hex to char array c++ Commented Jun 26, 2021 at 23:36
  • @kaylum Those answers are useless on the system having 2kB of RAM. No std at all. Commented Jun 26, 2021 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. stackoverflow.com/questions/17261798/… Commented Jun 26, 2021 at 23:42
  • no sorry, that method takes too much memory, as I only have 2kb. Commented Jun 27, 2021 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(). Commented Jun 28, 2021 at 1:14

1 Answer 1

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]);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.