使用十六进制表示法将缓冲区转换为字符串流: [英] Getting a buffer into a stringstream in hex representation:

查看:161
本文介绍了使用十六进制表示法将缓冲区转换为字符串流:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个缓冲区:

  uint8_t buffer [32] 

它完全填充了值,我怎么能得到它到字符串流,十六进制表示,

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

但是当我从stringstream中取出字符串时,具有值<



例如,如果数组中的字节1和2都是{32} {4},那么我们只需要一个字符来表示。 } my stringstream会有:

  204而不是2004 

我可以对stringstream应用格式化以添加0填充吗?我知道我可以用sprintf这样做,但是这些流已经用于很多信息,这将是一个很大的帮助,以这种方式实现。

解决方案

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


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.

解决方案

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

这篇关于使用十六进制表示法将缓冲区转换为字符串流:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆