0

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?

2
  • Another problem in your source: you are returning a pointer to a local variable, which is undefined behavior. Also, you are using non-standard extension of C++ - variable-length array. Commented Sep 16, 2020 at 15:07
  • i have noticed, so what you are suggesting to return? Commented Sep 16, 2020 at 15:13

1 Answer 1

4

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);
}
Sign up to request clarification or add additional context in comments.

3 Comments

This solved some of the errors, but not my main problem , it still doesn' t return as i want for some reasons..
@J.Steve As mentioned in another comment, the code you show returns a pointer to a local variable. But converted to BYTE. Use vectors, return the vector.
@Someprogrammerdude why this doesn't work if I change unsigned to uint8_t

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.