We had a little bit of fun in the 2nd Monitor this morning, one user greeted another with a hex string. It turned out that the user being greeted deals with Hex Dumps enough that they were able to read the string, but I wasn't so I created this converter.
What could I have done to reduce the dependency on cstring
?
How could I have made this more C++17 and less C Programming language.
#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
#include <cstring>
class HexStringToAsciiStringConverter
{
std::vector<unsigned> HexValues;
const char* Remove0x(const char* hxv)
{
if (std::strstr(hxv, "0x") == hxv)
{
hxv += 2;
}
return hxv;
}
void ConvertStringToUnsigned(std::string HexStringToConvert)
{
const char *hxv = Remove0x(HexStringToConvert.c_str());
while (*hxv && *(hxv+1))
{
char hxva[3] = {'\0'};
std::strncpy(hxva, hxv, 2);
HexValues.push_back(std::strtol(hxva, nullptr, 16));
hxv += 2;
}
}
public:
HexStringToAsciiStringConverter::HexStringToAsciiStringConverter(std::string Original)
{
ConvertStringToUnsigned(Original);
}
std::string HexStringToAsciiStringConverter::ConvertHexToString()
{
std::vector<unsigned char> tmpcarray;
for (auto HexValue: HexValues)
{
tmpcarray.push_back(HexValue);
}
std::string output(tmpcarray.begin(), tmpcarray.end());
return output;
}
};
int main() {
std::string Original = "0x486920446f6e2c20686f7727732073706163653f";
HexStringToAsciiStringConverter Converter(Original);
std::cout << Converter.ConvertHexToString() << std::endl;
return EXIT_SUCCESS;
}