1

having real trouble with this simple issue. I have a string like this:

std::string msg = "00 00 00 00 00 06 01 05 00 FF 00 00";

which i would like to:

unsigned char bbuffer[12] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x01, 0x05, 0x00, 0xFF, 0x00, 0x00 };

what is the way to do it?

1 Answer 1

7

If at all possible, I'd advise using a std::vector<unsigned char> instead of an actual array.

Using that, I guess I'd do something like this:

std::istringstream buffer(msg);

std::vector<unsigned char> bbuffer;

unsigned int ch;
while (buffer >> std::hex >> ch)
    bbuffer.push_back(ch);

If you really insist on the array, you could do something like:

std::istringstream buffer(msg);

char bbuffer[12];

unsigned int ch;
for (int i=0; buffer >> std::hex >> ch; i++)
    bbuffer[i] = ch & 0xff;

But the vector is usually preferable.

Sign up to request clarification or add additional context in comments.

2 Comments

I was so close! I'll get you next time ;)
great.thnx. i was using vector internally anyway

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.