Go Down

Topic: Parse string as Hex? (Read 1 time) previous topic - next topic

SoundGuyAndy

I'm trying to clean up entry of some Hex strings in a project I'm working on, and am running up against what I'm sure is a pretty simple problem that's just slightly beyond my comprehension of C at this point.

Right now, I'm declaring the data as an array, such as:

byte PressNext[]={
 0x90, 0x02, 0x7F};

And then, when I need to send that out the serial port, I do a sizeof on the array to get it's length (since the length may vary), then loop a

Serial.print(PressNext, BYTE);

to send each byte of the array.

I'm trying to figure out a more streamlined/elegant way to do this, so that I can enter the string as a straight string without the 0x indicator and the comma delimiter, so I guess I'm trying to treat an ASCII char string as hex values?

In other words, I want to be able to declare the string as

"90 02 7F"

Instead of having to format it as "0x90, 0x02, 0x7F"

So, the twofold question is how do I parse that char string into the proper Hex values, and then is my Serial.print loop the best way to do it, or can I print it as a string in one piece without having to worry about getting the length and looping?

I think what I need to do is parse it into the Hex array, and then convert that back to a char string? Or am I overthinking?

Thanks,
Andy

drhex

Quote
In other words, I want to be able to declare the string as

"90 02 7F"

Instead of having to format it as "0x90, 0x02, 0x7F"


Why do you want to do that? Too lazy to type the 0x and commas?
The string version that you propose would consume 3 times as much memory.

SoundGuyAndy

Memory isn't a major issue.

And assume that I need to do it that way because I'm getting the strings from an input that I don't have control over, so I don't have a choice.

PaulS

Parsing input like "90 02 7F" is pretty straightforward. There is a string library that contains an indexOf method. If the string contains a space, as it does after the first 0, there are two or more tokens in the string and the first token ends just before the space. If there is no space, there is only one token and it is the complete string.

Once you have tokens ("90", "02", "7F"), adding the 0x string in front is easy. Now you have "0x90", "0x02", and "0x7F".

You can then convert these strings to numbers (0x90, 0x02, 0x7F) using sscanf with the %x format specifier.

Go Up