2

I am new in C++, I usually use C. But now, I just find a good library that compress some information, with a special algorithm that it is very useful to my project. Then this library gave me as an answer: binary data which lives in a stringstream object. Since it is binary data, there are some bytes that are not an ASCII character. So what I want to do is extract the data and got their hexadecimal representation. How I can do it? I have the following code:

stringstream ss; \\variable in which I got the result from the library
bitset1.write(ss); \\with this instruction I got the binary information from the library

From there I try the following things:

1) Just print:

cout << hex << ss;

2) Use the str method.

cout << hex << ss.str();

3) Use the read buffer method.

cout << hex << ss.rdbuf();

So, I think I am missing something, or maybe a lot, someone can help me?

1 Answer 1

2

If a shortcut exists, I do not know it. However, this does what you want:

std::cout << std::hex << std::setfill('0');
const std::string s = ss.str();
const size_t slen = s.length();
for (size_t i = 0; i < slen; ++i) {
    const unsigned char c = s[i];
    const unsigned int n = c;
    std::cout << std::setw(2) << n;
}
std::cout << "\n";

The key is to use a non-char integer type for output, since the stream insertion operator << treats char specially.

Sign up to request clarification or add additional context in comments.

7 Comments

Calling ss.str() repeatedly is abysmal for efficiency. Call it once and cache it.
@thb it works perfectly well thanks a lot, also I just callit once ss.str(). Now, i just will like to know how to do the invers process if I have a string how I load a StringStream variable?
@user1462592 : std::stringstream ss(my_string_object); It's not like documentation isn't readily available...
@ildjarn well in did the question is: how to load a String that has hexadecimal representation of a binary data to a stringstream
@user1462592 : I showed exactly how in the comment you just replied to.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.