Reputation: 17
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?
Upvotes: 0
Views: 632
Reputation: 409166
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);
}
Upvotes: 4