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!
-
1there 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 valuejsotola– jsotola2020年05月07日 04:58:50 +00:00Commented May 7, 2020 at 4:58
-
1@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– Amir2020年05月07日 05:04:55 +00:00Commented May 7, 2020 at 5:04
-
Related: How to convert a hex string to an array of bytes?Gabriel Staples– Gabriel Staples2020年08月06日 01:28:49 +00:00Commented Aug 6, 2020 at 1:28
2 Answers 2
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();
-
1If 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– Majenko2020年05月07日 09:51:36 +00:00Commented May 7, 2020 at 9:51 -
@Majenko, thanks and upvoted for your comment, make the code cleaner and simpler. I updated my answer.hcheung– hcheung2020年05月07日 11:14:30 +00:00Commented May 7, 2020 at 11:14
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
.