简体   繁体   中英

How to log a hex string in c++ with ostringstream?

I'm trying to log hex values to an ostringstream, but it's not working. I'm trying:

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;

I'm expecting to get something like "0x00 0x01 0xab 0xcd" but instead I get "0x00".

I also tried breaking it up like

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

but get the same thing.

The issue is that the characters are not treated as integers in output stream and so the integer manipulators do not affect their output.

Basically ... replace

unsigned char buf[4];

With

unsigned int buf[4];

This works:

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

I've added casts to (int) and change setw(2).

I assume, that the mainproblem here is the interpretation of char by your stringstream. Try to cast it to int and everything works like charm:

#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;
}

This gives you your desired output:

0x00 0x01 0xab 0xcd 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM