Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert a set of hex strings to byte array

Tags:

c++

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?

like image 502
Dean Avatar asked Dec 21 '12 16:12

Dean


2 Answers

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 );
}
like image 72
sean Avatar answered Nov 14 '22 22:11

sean


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
like image 31
Itsik Avatar answered Nov 14 '22 23:11

Itsik