c++ - 如何从 C++ 中的 stringstream 变量中提取二进制数据?

标签 c++

我是 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/

相关文章:

c++ - 没有 GLkit 的 OpenGL ES。 GLKMatrix 的类似物和纯 OpenGL ES 中的函数

C++,控制台应用程序,从目录读取文件

c++ - 从Poisson分布中提取数字的性能较低

c++ - 我如何拆除多线程 C++ 中的观察者关系?

c++ - 如何将整数初始化为 "a = {1,}"编译?

c++ - 返回 double 组时出错

c++ - 如何同时使用并行和串行版本的 MKL?

c++ - 一组类型的模板特化

c++ - stringstream object() 和 object 有什么区别?

c++ - 来自 std::unordered_set<char> 的有效构造 std::string