So you have text reading "55DEBEFF4A". Let's assume that's ASCII because it 's a lot harder and a lot rarer than the alternatives. To turn this into bytes, you're going to have to work through the characters and convert the suckers character by character.
Here are a couple borderline horrible ways to do the translation that hopefully will suggest better ways to do it.
An ugly map-based approach:
std::map<char, int> cnv
{
{'0', 0},
{'1', 1},
{'2', 2},
{'3', 3},
{'4', 4},
{'5', 5},
{'6', 6},
{'7', 7},
{'8', 8},
{'9', 9},
{'a', 10},
{'b', 11},
{'c', 12},
{'d', 13},
{'e', 14},
{'f', 15},
{'A', 10},
{'B', 11},
{'C', 12},
{'D', 13},
{'E', 14},
{'F', 15}
};
std::vector<uint8_t> binarray(const std::string & in)
{
std::vector<uint8_t> out;
bool newnum = true;
size_t loc = 0;
for (char val: in)
{
if (newnum)
{
out.push_back(cnv[val]);
newnum = false;
}
else
{
out [loc] <<= 4;
out [loc] +=cnv[val];
++loc;
newnum = true;
}
}
return out;
}
And here's one taking advantage of iostreams:
std::vector<uint8_t> binarray2(const std::string & in)
{
std::vector<uint8_t> out;
std::stringstream cnv;
bool newnum = true;
for (char ch:in)
{
cnv << ch;
if (newnum)
{
newnum = false;
}
else
{
cnv << ' ';
newnum = true;
}
}
int val;
cnv >> std::hex;
while (cnv >> val)
{
out.push_back(val);
}
return out;
}
Note they both return std::vector
. You can pass around the vector easily, it contains all the sizing information you need, and it manages its own memory. You can use std::vector::data
to get the byte array you need. All you have to do is keep the vector around until you aye done with the byte array or it will free the array out from underneath you.