1

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?

4

1 回答 1

1

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.

于 2012-06-18T02:47:55.227 回答