如何将字符数组转换为基于字符串的十六进制流(ostringstream)
在 C++ 中(在使用 gcc 的 Linux 上)我想将字节数组(vector
)放入 ostringstream
或 string
。
我知道我可以使用 sprintf,但它似乎也不是使用 char* 的最佳方法。
顺便说一句: 此链接没有帮助
编辑: 到目前为止,所有答案都有效。但我并不是说我想将字节/十六进制值转换为其字符串表示形式,例如 vector<..> = {0,1,2} ->字符串 =“000102”
。抱歉缺少但重要的细节
in C++ (on Linux with gcc) I'd like to put a byte array (vector<unsigned char>
) to a ostringstream
or a string
.
I know that I can use sprintf
but it doesn't seem to be the best way to use char*
also.
Edit: All answer work so far. But I did not meantion, that I'd like to convert the bytes/hex-values into their string representation, e.g., vector<..> = {0,1,2} -> string = "000102"
. Sorry for that missing but important detail
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
获得赞成票的机会很小,但由于这正是OP所要求的,并且没有其他答案,包括所选的答案,奇怪的是,这样做:
备用流转储 strong>
如果您只想转储一个 unsigned char 固定数组,则以下操作将轻松执行此操作,几乎没有任何开销。
当我想将固定缓冲区转储到 ostream 衍生物时,我总是使用它。这个调用非常简单:
Little chance of getting an up-vote, but since it is exactly what the OP asked for, and no other answer, including the selected one, oddly, does so:
Alternate Stream Dump
If all you want to do is dump an unsigned char fixed array the following will handily do so, which almost no overhead at all.
I use this all the time when I want to dump fixed buffers to an ostream derivitive. The call is dead-simple:
从向量 char arr 到 stl 字符串:
从 stl 字符串到向量 char 数组:
From vector char arr to stl string:
From stl string to vector char array:
对于 setw include:
这应该将 01 放入流中:
For setw include:
This should put 01 in stream:
使用 boost:: alogorithm::hex
对于 std::ostream
对于 std::string
Use boost::alogorithm::hex
For std::ostream
For std::string
那么您想将字符向量的数据放入字符串中吗?简单的:
So you want to put the data of a vector of chars into a string? Easy: