c++hexostringstream

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.


Solution

  • 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