1

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:

String 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!

Gabriel Staples
  • 1,369
  • 11
  • 27
Amir
  • 31
  • 3

2 Answers2

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();

Gabriel Staples
  • 1,369
  • 11
  • 27
hcheung
  • 1,361
  • 7
  • 13
  • 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 07 '20 at 09:51
  • @Majenko, thanks and upvoted for your comment, make the code cleaner and simpler. I updated my answer. – hcheung May 07 '20 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.

Gabriel Staples
  • 1,369
  • 11
  • 27
rubemnobre
  • 33
  • 4