0

My apologies if this is a naive question. How do I convert a String which has hex values to a byte array that has those hex values?

This:

Stirng s = "0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff";

Needs to be converted to this:

char test[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};

I used the following procedure. It does convert it, however, each character is saved as a character as opposed to hex value:

unsigned int str_len = s.length()+1; char charArray[str_len]; s.toCharArray(charArray, str_len);

Any help will be appreciated. Thank you!

  • there is no such thing as a hex byte ... it is simply an 8 bit number ... you could use 0xff or 255 because they are the same value – jsotola May 7 at 4:58
  • @jsotola This is just an example, I need this to be used for all hex values. How do I convert the string to byte array? – Amir May 7 at 5:04
3

You only convert the String object to a char array. It need to further split the char array into substring, and then convert it to number.

To split the char array, you can use strtok() function in c++ to do the job.

There is no str conversion function that can convert "0xff" into uint8_t directly. However, as @rubemnobre mentioned strtol() can be used to convert a c string to a long (in Arduino, it is 4-byte number) and further cast into a uint8_t and store in a byte array.

String s = "0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff";

// Convert String object to char array
unsigned int str_len = s.length()+1;
char charArray[str_len];
s.toCharArray(charArray, str_len);

uint8_t byteArray[7];
int i=0;

// split charArray at each ',' and convert to uint8_t
char *p = strtok(charArray, ",");
while(p != NULL) {
  byteArray[i++] = strtoul(p, NULL, 16);
  p = strtok(NULL, ",");
}

// Print the byteArray
for (i=0; i<sizeof(byteArray)/sizeof(char); i++) {
  Serial.print(byteArray[i]);
  Serial.println(", ");
}
Serial.println();
| improve this answer | |
  • 1
    If you're not strtol's using "endptr" (&ptr in your case) you can just replace it with NULL and the parameter will be ignored. Also if you're casting to uint8_t then strtoul would be a better choice. – Majenko May 7 at 9:51
  • @Majenko, thanks and upvoted for your comment, make the code cleaner and simpler. I updated my answer. – hcheung May 7 at 11:14
2

There are C functions that can convert text to number. For example, strtol() or atoi(). Here is a little snippet to get you started:

char *str = "FF";
char *ptr;
int result = strtol(str, &ptr, 16); //the 16 is the base the string is in (HEX -> base 16)

result will have 0xFF or 255 by the end. You can use this to achieve what you are trying to do. Take a look at this for functions you can use to manage your String.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.