简体   繁体   中英

String of Bytes to Byte array c++

Im trying to make function that takes this pattern string :

"07 C5 8F E1 FD CA 8C E2 D4 FD BC E5 03 C6 8F E2"

to return this BYTE array

BYTE pattern[] = { 0x07, 0xC5, 0x8F, 0xE1, 0xFD, 0xCA, 0x8C, 0xE2, 0xD4, 0xFD, 0xBC, 0xE5, 0x03,  0xC6, 0x8F, 0xE2};

What i tried:

BYTE strPatternToByte(std::string pattern, int len)
{
    std::vector<std::string> tokens;
    std::string token;
    std::istringstream tokenStream(pattern);
    while(std::getline(tokenStream, token, ' '))
    {
        tokens.push_back(token);
    }
    BYTE somePtr[len];
    for ( int i=0 ; i < len ; i++)
    {
        somePtr[i] = '0x' +  tokens[i];
    }

    return somePtr;
}

but the line to convert to pattern of bytes didn't work for me,

somePtr[i] = (byte) tokens[i];

is there a way in c++ to automatically parse them into bytes or something like in java?

The problem is that (byte) tokens[i] doesn't translate a string to another type, instead it asks the compiler to treat the std::string object in tokens[i] as a byte , which it isn't and can't be converted to. It's basically you telling a lie to the compiler. In fact, basically all C-type casting should be a red flag that you're doing something wrong.

One solution is to instead use the normal stream extraction operator >> to parse each space-delimited hexadecimal sequence as an unsigned integer:

std::vector<unsigned> values;
std::istringstream stream(pattern);

unsigned value;
while (stream >> std::hex >> value)
{
    values.push_back(value);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM