3

Here is a code sample that I am using to print the contents of a uint8_t vector in hex format.

#include <iostream>
#include <iomanip>
#include <cstdint>
#include <vector>

std::ostream& operator<<(std::ostream& o, const std::vector<uint8_t>& packet) {
    std::ios_base::fmtflags oldFlags = o.flags();
    std::streamsize oldPrec  = o.precision();
    char oldFill  = o.fill();

    o << std::showbase // show the 0x prefix
      << std::internal // fill between the prefix and the number
      << std::setfill('0'); // fill with 0s

    for (std::size_t i = 0; i < packet.size(); ++i) {
        o << std::setw(4) << std::hex << (int) packet[i] << " ";
    }

    o.flags(oldFlags);
    o.precision(oldPrec);
    o.fill(oldFill);

    return o;
}

int main() {
    std::vector<uint8_t> packet{0x81, 0x55, 0x00};
    std::cout << packet << "\n";
} 

This prints the following:

0x81 0x55 0000

I want that last 0000 to show up as 0x00. How can I achieve this?

PS: I looked at couple of questions regarding printing 0x00 but answers on those questions prints 0000 for me as well.

meguli
  • 1,426
  • 1
  • 18
  • 35
  • There's the obvious way `if (packet[i] == 0) o << "0x00" ...`, but I'm surprised that's necessary. Is this a bug? – john Sep 13 '18 at 08:41
  • try `cout << "0x" << setfill('0') << setw(2) << hex << 00 << endl;` from https://stackoverflow.com/q/5760252/4848659 – Gimhani Sep 13 '18 at 08:42
  • 1
    The issue is discussed here [std::showbase fails for hex value 0](https://bugzilla.redhat.com/show_bug.cgi?id=166735) – tunglt Sep 13 '18 at 08:49
  • Also relevant: https://stackoverflow.com/questions/8513169/why-is-0-zero-printed-without-leading-0x-with-c-printf-format-x#8513429 – AMA Sep 13 '18 at 09:15
  • I went with doing something special for 0, as indicated by other questions also given here. I asked this to see if there is a uniform way but does not seem to be the case. – meguli Sep 13 '18 at 10:03

0 Answers0