将缓冲区放入十六进制表示的字符串流中:
如果我有一个像这样的缓冲区:
uint8_t buffer[32];
并且它完全被值填满,我怎样才能将它放入十六进制表示的字符串流中,并在小值上用 0 填充?
我尝试过:
std::stringstream ss;
for (int i = 0; i < 32; ++i)
{
ss << std::hex << buffer[i];
}
但是当我从字符串流中取出字符串时,我遇到了一个问题:值的字节数 < 16只用一个字符来表示,我希望它们被0填充。
例如,如果数组中的字节 1 和 2 为 {32} {4} 我的字符串流将具有:
204 instead of 2004
我可以将格式应用于字符串流以某种方式添加 0 填充吗?我知道我可以使用 sprintf 来做到这一点,但是流已经被用于大量信息,并且以某种方式实现这一点将有很大帮助。
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?
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.
For example if bytes 1 and 2 in the array were {32} {4} my stringstream would have:
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
查看流修饰符:std::setw 和 std::setfill。它会对你有所帮助。
Look at the stream modifiers:
std::setw
andstd::setfill
. It will help you.您可以使用 C++20
std::format
:在
std::format
广泛使用之前,您可以使用{fmt } 库,std::format
基于。 {fmt} 还提供了join
函数,使这变得更加容易 (godbolt) :免责声明:我是 {fmt} 和 C++20
std::format
的作者。You can do this with C++20
std::format
:Until
std::format
is widely available you can use the {fmt} library,std::format
is based on. {fmt} also provides thejoin
function that makes this even easier (godbolt):Disclaimer: I'm the author of {fmt} and C++20
std::format
.