5

I have an input of char *str = "13 00 0A 1B CA 00";

I need an output as BYTE bytes[] = { 0x13, 0x00, 0x0A, 0x1B, 0xCA, 0x00 };

can somebody help with a solution?

2
  • 1
    sscanf might work, but he may not know the exact number of bytes in the string, so he needs a more dynamic approach. Commented Dec 21, 2012 at 16:08
  • sscanf is not safe, it causes 'buffer overrun'. stackoverflow.com/questions/5873402/… Commented Dec 21, 2012 at 16:21

2 Answers 2

7

You will need to parse out each of the two characters and then convert them into BYTE. This isn't fairly difficult to do.

std::stringstream converter;
std::istringstream ss( "13 00 0A 1B CA 00" );
std::vector<BYTE> bytes;

std::string word;
while( ss >> word )
{
    BYTE temp;
    converter << std::hex << word;
    converter >> temp;
    bytes.push_back( temp );
}
Sign up to request clarification or add additional context in comments.

6 Comments

Which c++ compiler are you using that has a function named hex_string_to_int in the standard library?
I'm sorry that is not exactly what I ment, I'm going to change that.
I didn't quite understand this, can you explain in more detail please>
my strings are "xx xx xx xx" format, will strstream work with the spaces?
typedef unsigned short BYTE;
|
2

This answer assumes that the input format is actually 3 chars for each hex BYTE. I used sscanf for simplicity, streams are obviously also an option.

    std::vector<BYTE> bytes;
    char *str = "13 00 0A 1B CA 00";
    std::string input(str);

    size_t count = input.size()/3;
    for (size_t i=0; i < count; i++)
    {           
        std::string numStr = input.substr(i*3, input.find(" "));

        int num=0;
        sscanf(numStr.c_str(), "%x", &num);
        bytes.push_back((BYTE)num);
    }

    // You can access the output as a contiguous array at &bytes[0]
    // or just add the bytes into a pre-allocated buffer you don't want vector

1 Comment

Actually count of bytes is (input.size() + 1)/3. Your code will miss last byte in input string.

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.