Note that there are some explanatory texts on larger screens.

plurals
  1. POc++ insert to a stream with formatting for hex
    primarykey
    data
    text
    <p>I often do something like:</p> <pre><code>uint8_t c=some_value; std::cout &lt;&lt; std::setfill('0') &lt;&lt; std::setw(2); std::cout &lt;&lt; std::hex &lt;&lt; int(c); std::cout &lt;&lt; std::setfill(' '); </code></pre> <p>(in particular while dumping debugging information). Wouldn't it be nice to have something manipulatorish that I could put in a stream like this:</p> <p>std::cout &lt;&lt; "c value: 0x" &lt;&lt; hexb(c) &lt;&lt; '\n';</p> <p>that would do all of that? Does anyone know how to do that?</p> <p>I've gotten this to work but would love to have a simpler way:</p> <pre><code>#include &lt;iostream&gt; #include &lt;iomanip&gt; class hexcdumper{ public: hexcdumper(uint8_t c):c(c){}; std::ostream&amp; operator( )(std::ostream&amp; os) const { // set fill and width and save the previous versions to be restored later char fill=os.fill('0'); std::streamsize ss=os.width(2); // save the format flags so we can restore them after setting std::hex std::ios::fmtflags ff=os.flags(); // output the character with hex formatting os &lt;&lt; std::hex &lt;&lt; int(c); // now restore the fill, width and flags os.fill(fill); os.width(ss); os.flags(ff); return os; } private: uint8_t c; }; hexcdumper hexb(uint8_t c) { // dump a hex byte with width 2 and a fill character of '0' return(hexcdumper(c)); } std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const hexcdumper&amp; hcd) { return(hcd(os)); } </code></pre> <p>When I do this: </p> <pre><code>std::cout &lt;&lt; "0x" &lt;&lt; hexb(14) &lt;&lt; '\n'; </code></pre> <ol> <li>hexb(c) is invoked and returns a hexcdumper whose constructor saves c</li> <li>the overloaded operator&lt;&lt; for hexcdumper invokes hexcdumper::operator() passing it the stream</li> <li>hexcdumper's operator() does all the magic for us</li> <li>after hexcdumper::operator() returns, the overloaded operator&lt;&lt; returns the stream as returned from hexcdumper::operator() so chaining works.</li> </ol> <p>On the output, I see:</p> <pre><code>0x0e </code></pre> <p>Is there a simpler way to do this?</p> <p>Patrick</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload