0

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.

Thundercleez
  • 327
  • 1
  • 4
  • 18
  • 1
    Possible duplicate of [how do I print an unsigned char as hex in c++ using ostream?](https://stackoverflow.com/questions/673240/how-do-i-print-an-unsigned-char-as-hex-in-c-using-ostream) – Alan Birtles Mar 11 '19 at 15:07

3 Answers3

1

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];
Öö Tiib
  • 10,809
  • 25
  • 44
1

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).

battlmonstr
  • 5,841
  • 1
  • 23
  • 33
1

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 
Tom Mekken
  • 1,019
  • 1
  • 12
  • 27