The string
shown is already in a hex representation. What you are really asking for is to DECODE that hex back to its original binary data, and then print that data as hex. Which is redundant. Just print the string
as-is, inserting a space after every 2nd character, eg:
std::string keyInStr = "1314191A1B";
for (int i = 0; i < keyInStr.size(); i += 2)
{
//printf("%.2s ", keyInStr.c_str()+i);
std::cout << keyInStr.substr(i, 2) << " ";
}
Otherwise, if you intend to actually use the key binary data, then you do need to decode the string, eg:
unsigned char hex2dec(const std::string &s, size_t pos)
{
char ch = s[pos];
if (ch >= 'A' && ch <= 'F')
return (ch - 'A') + 10;
if (ch >= 'a' && ch <= 'f')
return (ch - 'a') + 10;
if (ch >= '0' && ch <= '9')
return (ch - '0');
// error!
}
unsigned char decodeHexByte(const std::string &s, size_t pos)
{
return (hex2dec(s, pos) << 4) | hex2dec(s, pos+1);
}
std::string keyInStr = "1314191A1B";
unsigned char keyInHex[5] = {};
for (int i = 0, j = 0; i < 5; ++i, j += 2)
{
keyInHex[i] = decodeHexByte(keyInStr, j);
//printf("%02X ", keyInHex[i]);
std::cout << std::hex << std::setw(2) << std::setfill('0') << (int) keyInHex[i] << " ";
}
Live Demo
Alternatively, if you are using C++11 or later:
std::string keyInStr = "1314191A1B";
unsigned char keyInHex[5] = {};
for (int i = 0; i < 5; ++i)
{
keyInHex[i] = std::stoi(keyInStr.substr(i*2, 2), nullptr, 16);
//printf("%02X ", keyInHex[i]);
std::cout << std::hex << std::setw(2) << std::setfill('0') << (int) keyInHex[i] << " ";
}
Live Demo