开发者

Getting a buffer into a stringstream in hex representation:

开发者 https://www.devze.com 2023-04-11 00:05 出处:网络
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 represen开发者_如何学Ctation, with 0-padding on small

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 represen开发者_如何学Ctation, 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.


#include <sstream>
#include <iomanip>

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]);
}


Look at the stream modifiers: std::setw and std::setfill. It will help you.


You can do this with C++20 std::format:

std::stringstream ss;
for (int i = 0; i < 32; ++i) {
  ss << std::format("{:02}", buffer[i]);
}

Until std::format is widely available you can use the {fmt} library, std::format is based on. {fmt} also provides the join function that makes this even easier (godbolt):

std::string s = fmt::format("{:02}", fmt::join(buffer, ""));

Disclaimer: I'm the author of {fmt} and C++20 std::format.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号