Я бы пошел на простые простые петли
int hexValue(int c)
{
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
return -1;
}
std::vector<unsigned char> toBin(const std::string& s)
{
std::vector<unsigned char> result;
for (int i=0,n=s.size(); i<n-1; i+=2)
{
int x1 = hexValue(s[i]);
int x2 = hexValue(s[i+1]);
if (x1 >= 0 && x2 >= 0)
result.push_back(x1*16 + x2);
}
return result;
}
std::string toHex(const std::vector<unsigned char>buf)
{
const char *hex = "0123456789ABCDEF";
int n = buf.size();
std::string result(n*2, ' ');
for (int i=0; i<n; i++)
{
result[i*2] = hex[buf[i]>>4];
result[i*2+1] = hex[buf[i]&15];
}
return result;
}
Если вам нужно, чтобы это преобразование было очень быстрым (при условии, что ввод достаточно большой и формально правильный) ...
std::vector<unsigned char> toBin(const std::string& s)
{
static unsigned char H[256], L[256];
if (L['1'] == 0)
{
for (int i=0; i<10; i++)
{
H['0'+i] = (i<<4);
L['0'+i] = i;
}
for (int i=0; i<6; i++)
{
H['a'+i] = H['A'+i] = ((10+i)<<4);
L['a'+i] = L['A'+i] = (10+i);
}
}
std::vector<unsigned char> result(s.size()>>1);
for (int i=0,n=s.size(); i<n-1; i+=2)
result[i>>1] = H[s[i]]+L[s[i+1]];
return result;
}