<rant> Good grief, working with strings in C is just painful </rant>I'm looking for an efficient way to extract ASCII-encoded bytes from a character buffer. For instance, I have the following MODBUS data packet received from a slave instrument (hex format):
3A 30 31 30 33 30 32 30 32 42 45 33 41 0D 0A
This instrument and my driver are working in the ASCII domain, so this actually looks like:
:01030202BE3A\r\n
Now the trick here is that certain groups of bytes must be "lumped" together to be understood. For instance, here is how I will need to parse these into the appropriate elements of the protocol:
element byte width data type
: 1 char
01 2 char
03 2 char
02 2 char
02BE 4 short
3A 2 char
\r 1 char
\n 1 char
Not really a big deal, but I'd like to avoid "hard-coding" some of these widths, particularly when dealing with variable output register data.
I had planned to use sscanf to parse these out of the string, but I discovered that you can't use variable width specifiers ( %*X ) like you can with sprintf.
For instance, here's what I do to build my ASCII MODBUS queries:
sprintf(query,
"%c%s%0*X%s",
MODBUS_MSG_Header, // :
qryPayload, // string
MODBUS_MSG_LRC_LEN, // 2
Modbus_CalcLRC(qryPayload), // lLRC
MODBUS_MSG_Trailer); // CR LF
Then I looked into using the CVI formatio.h Scan function. It has has something close:
s = "ffff";
Scan (s, "%s>%x[b2]", &a); /* result: a = 65535
But it doesn't appear that I can handle adjacent characters in an array with no whitespace.
Am I (probably) overlooking something simple here?