如何使用OSTRINGSTREAM将C 中的十六进制字符串记录



我正在尝试将十六进制值记录到ostringstream,但它不起作用。我正在尝试:

unsigned char buf[4];
buf[0] = 0;
buf[1] = 1;
buf[2] = 0xab;
buf[3] = 0xcd;
std::ostringstream e1;
e1 << "0x" << std::setfill('0') << std::setw(3) << std::hex << buf[0] << " " << "0x" << std::setfill('0') << std::setw(3) << std::hex << buf[1] << " " << "0x" << std::setfill('0') << std::setw(3) << std::hex << buf[2] << " " << "0x" << std::setfill('0') << std::setw(3) << std::hex << buf[3];
std::cout << e1.str() << std::endl;

我希望能得到类似" 0x00 0x01 0xab 0xcd"之类的东西,但是我得到了" 0x00"。

我也尝试像

一样打破它
    e1 << "0x" << std::setfill('0') << std::setw(3) << std::hex << buf[0];
    e1 << " ";
    e1 << "0x" << std::setfill('0') << std::setw(3) << std::hex << buf[1];
    e1 << " ";
    e1 << "0x" << std::setfill('0') << std::setw(3) << std::hex << buf[2];
    e1 << " ";
    e1 << "0x" << std::setfill('0') << std::setw(3) << std::hex << buf[3];

但是得到同样的东西。

我假设,这里的主题是您的弦乐对char的解释。尝试将其投入到int,一切都像魅力一样工作:

#include <iostream>
#include <sstream>
#include <iomanip>
using namespace std;
int main()
{
  unsigned char buf[4];
  buf[0] = 0;
  buf[1] = 1;
  buf[2] = 0xab;
  buf[3] = 0xcd;
  ostringstream e1;
  for (uint i=0; i< sizeof(buf); ++i)
  {
    e1  << "0x" << std::setw(2) << std::setfill('0') << std::hex << static_cast<int>(buf[i]) << " ";
  }
  cout << e1.str() << endl;
  return 0;
}

这为您提供了所需的输出:

0x00 0x01 0xab 0xcd 

问题是字符不被视为输出流中的整数,因此整数操纵器不会影响其输出。

基本上...替换

unsigned char buf[4];

unsigned int buf[4];

这有效:

e1         << "0x" << std::setfill('0') << std::setw(2) << std::hex << (int)buf[0]
    << " " << "0x" << std::setfill('0') << std::setw(2) << std::hex << (int)buf[1]
    << " " << "0x" << std::setfill('0') << std::setw(2) << std::hex << (int)buf[2]
    << " " << "0x" << std::setfill('0') << std::setw(2) << std::hex << (int)buf[3];

我添加了(int)的铸件并更改setW(2)。

最新更新