我是 C++ 新手,我通常使用 C。但现在,我只是找到一个很好的库,可以压缩一些信息,具有特殊的算法,这对我的项目非常有用。然后这个库给了我答案:存在于 stringstream 对象中的二进制数据。由于是二进制数据,因此有一些字节不是 ASCII 字符。所以我想做的是提取数据并得到它们的十六进制表示。我怎样才能做到呢? 我有以下代码:
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
从那里我尝试以下操作:
1)只需打印:
cout << hex << ss;
2)使用str方法。
cout << hex << ss.str();
3)使用读缓冲区方法。
cout << hex << ss.rdbuf();
所以,我想我错过了一些东西,或者可能错过了很多,有人可以帮助我吗?
最佳答案
如果存在快捷方式,我不知道。但是,这符合您的要求:
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";
关键是使用非char
用于输出的整数类型,因为流插入运算符 <<
款待char
特别是。
关于c++ - 如何从 C++ 中的 stringstream 变量中提取二进制数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11076384/