c++ - 将 unsigned char* 转换为 std::istream* C++
问题描述
我必须将二进制数据(无符号字符 *)传递给以 std::istream 作为参数的函数 PerformRequest。哪个最好
unsigned char* data // has the binary data
PerformRequest(std::istream* in)
{
//some implementation
}
解决方案
您可以使用std::stringstream
from <sstream>
,它同时支持istream
和ostream
接口。因此,您可以通过 -interface 写入数据ostream
,然后将其作为istream
-argument 传递:
#include <sstream>
#include <iomanip>
#include <iostream>
void prints(istream &is) {
unsigned char c;
while (is >> c) {
std::cout << "0x" << std::hex << (unsigned int)c << std::endl;
}
}
int main()
{
unsigned char x[6] = { 0x2, 0x10, 0xff, 0x0, 0x5, 0x8 };
std::stringstream xReadWrite;
xReadWrite.write((const char*)x, 6);
prints(xReadWrite);
}
推荐阅读
- ios - 在 Apple Watch 模拟器中打开网页
- corda - 如何在通过 IntelliJ 运行 cordapp 时配置公证节点
- python-3.x - openGL 和 PyQt5 的问题
- express - 对 express.js 中的中间件排序感到困惑?
- spring-boot - 找到注释@EnableCircuitBreaker,但没有实现。你忘了包括一个开胃菜吗?
- python - sklearn中的随机状态意义
- javafx - JavaFX游戏动画如何根据角度在X轴和Y轴移动ImageView
- vim - YouCompleteMe 更改装订线外观
- chrome-web-store - 将扩展程序上传到 chrome 网上商店时出错
- android - 带有背景和文本的自定义浮动操作按钮