Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

is there an easy way to convert an ASCII std::string to HEX? I don't want to convert it to a number, I only want to convert each ASCII character to it's HEX value. The output format should also be a std::string. i.e.: "TEST" would be "0x54 0x45 0x53 0x54" or some similar format.

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
491 views
Welcome To Ask or Share your Answers For Others

1 Answer

If you don't care about the 0x it's easy to do using 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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...