I have a string which I send to the arduino using serial monitor. Something like that:
my specific string 0x0F 0x2C 0x98 0xBC
How can I parse this string in the arduino to get an array of hex values:
0x0F 0x2C 0x98 0xBD
? There are two prerequisites:
- All hexadecimal starts with
#
- The size of hexadecimal is 2. No
0x111
or '0xbbb'
2 Answers 2
How can I parse this string in the arduino to get an array of hex values:
There are a few standard library (stdlib) functions that can help you with that. Below is a snippet:
char buf[] = "0x0F 0x2C 0x98 0xBD";
uint8_t val[4];
void setup()
{
Serial.begin(9600);
char* bp = buf;
int i = 0;
do {
char* ep;
val[i] = strtol(bp, &ep, 16);
Serial.println(val[i], HEX);
bp = ep;
i += 1;
} while (*bp != 0);
}
void loop()
{
}
Cheers!
You can try reading each character and convert it to hexadecimal representation. I suppose you wanna 1 byte each value in hexadecimal representation, so, let's start.
For example the string "0x25", ignore the 0x and read the '2' and save it into a char variable. Same for '5';
char highBits = '2' - '0'; // convert to decimal representation
char lowBits = '5' - '0';
byte = (highBits << 4 | lowBits);
Now, save it inside you array. Make sure you check if the value is one of the possible letters in hexadecimal and convert it properly (A=10 and so on). Just include an if statement if it is a letter and convert it.
#
, as you wrote in the text, or with a0x
, like in the example?