Convert ASCII std :: string to hex

Is there an easy way to convert ASCII std :: string to HEX? I do not want to convert it to a number, I only want to convert each ASCII character to a HEX value. The output format should also be std :: string. that is: "TEST" will be "0x54 0x45 0x53 0x54" or in some similar format.

I found this solution, but maybe there is a better one (without converting a string to int to convert strings):

std::string teststring = "TEST"; std::stringstream hValStr; for (std::size_t i=0; i < teststring.length(); i++) { int hValInt = (char)teststring[i]; hValStr << "0x" << std::hex << hValInt << " "; } 

Thanks,
/ Mspoerr

+6
source share
2 answers

If you care about 0x, this is easy to do with std::copy :

 #include <algorithm> #include <sstream> #include <iostream> #include <iterator> #include <iomanip> namespace { const std::string test="hello world"; } int main() { std::ostringstream result; result << std::setw(2) << std::setfill('0') << std::hex << std::uppercase; std::copy(test.begin(), test.end(), std::ostream_iterator<unsigned int>(result, " ")); std::cout << test << ":" << result.str() << std::endl; } 
+6
source

This answer to another question does what you want, I think. You need to add the argument " " as a separator for ostream_iterator to get spaces between characters.

+4
source

Source: https://habr.com/ru/post/888028/


All Articles