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?

Dean
  • 499
  • 6
  • 13
  • 34
  • 1
    `sscanf` might work, but he may not know the exact number of bytes in the string, so he needs a more dynamic approach. – sean Dec 21 '12 at 16:08
  • sscanf is not safe, it causes 'buffer overrun'. http://stackoverflow.com/questions/5873402/is-sscanf-considered-safe-to-use – alex Dec 21 '12 at 16:21

2 Answers2

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 );
}
sean
  • 3,955
  • 21
  • 28
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
Itsik
  • 3,920
  • 1
  • 25
  • 37
  • Actually `count` of bytes is `(input.size() + 1)/3`. Your code will miss last byte in input string. – renadeen Dec 02 '13 at 14:38