C++ 以十六进制表示将缓冲区放入字符串流中:
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7639656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting a buffer into a stringstream in hex representation:
提问by John Humphreys - w00te
If I had a buffer like:
如果我有一个缓冲区,如:
uint8_t buffer[32];
and it was filled up completely with values, how could I get it into a stringstream, in hexadecimal representation, with 0-padding on small values?
并且它完全被值填满了,我怎么能把它变成一个字符串流,以十六进制表示,在小值上填充 0?
I tried:
我试过:
std::stringstream ss;
for (int i = 0; i < 32; ++i)
{
ss << std::hex << buffer[i];
}
but when I take the string out of the stringstream, I have an issue: bytes with values < 16 only take one character to represent, and I'd like them to be 0 padded.
但是当我从字符串流中取出字符串时,我遇到了一个问题:值 < 16 的字节只需要一个字符来表示,我希望它们被填充为 0。
For example if bytes 1 and 2 in the array were {32} {4} my stringstream would have:
例如,如果数组中的字节 1 和 2 是 {32} {4},我的 stringstream 将具有:
204 instead of 2004
Can I apply formatting to the stringstream to add the 0-padding somehow? I know I can do this with sprintf, but the streams already being used for a lot of information and it would be a great help to achieve this somehow.
我可以将格式应用于 stringstream 以某种方式添加 0-padding 吗?我知道我可以用 sprintf 来做到这一点,但是流已经被用于大量信息,以某种方式实现这一点会很有帮助。
回答by Dean Povey
std::stringstream ss;
ss << std::hex << std::setfill('0');
for (int i = 0; i < 32; ++i)
{
ss << std::setw(2) << static_cast<unsigned>(buffer[i]);
}
回答by Thomas Matthews
Look at the stream modifiers: std::setw
and std::fill
.
查看流修饰符: std::setw
和std::fill
。