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!

1
  • "in C++ there is no function like StringBuilder" - yes, there is. It's called std::ostringstream. Commented Feb 25, 2017 at 1:48

1 Answer 1

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();
}
Sign up to request clarification or add additional context in comments.

4 Comments

static_cast<int>() would be more idiomatic in C++ than the C-style cast (int).
If you want to append the 0x to the front, use std::showbase
@phoenix how would you go about converting this string back?
@anc: you can use std::hex and std::setw() with std::istringstream and operator>>

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.