I want to extract the hex code from a string and then insert the extracted hex codes into an array of bytes.
The length of the string and the number of hex numbers are unknown.
An example of what I want:
String myStr="07 12 b6 53 f2";
to
byte myByte[] = {0x07,0x12,0xb6,0x53,0xf2};
I'm new to arduino, can't get that code by myself
You could use a function like this to extract a number from your string.
uint8_t getHex(char const* str, size_t const index) {
return strtol(&str[3 * index], NULL, 16);
}
Example:
uint8_t myBytes[5]{};
for (size_t i = 0; i < 5; i++) {
myBytes[i] = getHex(myStr.c_str(), i);
}
for (size_t i = 0; i < 5; i++) {
Serial.print(myBytes[i], HEX);
Serial.print(' ');
}
Result:
7 12 B6 53 F2
1 Like
My suggestion become more complicated than I was thinking because I can't find a simple way to convert the token to byte.
void setup()
{
Serial.begin(115200);
String myStr = "07 12 b6 53 f2";
char *token;
token = strtok(myStr.c_str(), " ");
while (token != NULL)
{
Serial.println(token);
token = strtok(NULL, " ");
}
}
void loop()
{
}
The output is:
07
12
b6
53
f2
1 Like
Excellent, exactly what I wanted
system
Closed
December 31, 2022, 4:12am
8
This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.