2

Here is a that I write for Print a byte array to hex String , but now I want to save them as std::string and use it later

here is my code

typedef std::vector<unsigned char> bytes;
void printBytes(const bytes &in)
{
    std::vector<unsigned char>::const_iterator from = in.begin();
    std::vector<unsigned char>::const_iterator to = in.end();
    for (; from != to; ++from) printf("%02X", *from);
}

what can I do ?, I want to save it as a string not print(Show) in console window? any idea!

Selena
  • 23
  • 1
  • 5

1 Answers1

3

Use std::ostringstream:

typedef std::vector<unsigned char> bytes;
std::string BytesToStr(const bytes &in)
{
    bytes::const_iterator from = in.cbegin();
    bytes::const_iterator to = in.cend();
    std::ostringstream oss;
    for (; from != to; ++from)
       oss << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(*from);
    return oss.str();
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770