title: how do I print an unsigned char as hex in c++ using ostream?
body: <p>I want to work with unsigned 8-bit variables in C++.  Either <code>unsigned char</code> or <code>uint8_t</code> do the trick as far as the arithmetic is concerned (which is expected, since AFAIK <code>uint8_t</code> is just an alias for <code>unsigned char</code>, or so the debugger presents it.</p>
  
  <p>The problem is that if I print out the variables using ostream in C++ it treats it as char.  If I have:</p>
  
  <pre><code>unsigned char a = 0;
  unsigned char b = 0xff;
  cout &lt;&lt; "a is " &lt;&lt; hex &lt;&lt; a &lt;&lt;"; b is " &lt;&lt; hex &lt;&lt; b &lt;&lt; endl;
  </code></pre>
  
  <p>then the output is:</p>
  
  <pre><code>a is ^@; b is 377
  </code></pre>
  
  <p>instead of </p>
  
  <pre><code>a is 0; b is ff
  </code></pre>
  
  <p>I tried using <code>uint8_t</code>, but as I mentioned before, that's typedef'ed to <code>unsigned char</code>, so it does the same.  How can I print my variables correctly?</p>
  
  <p><strong>Edit:</strong> I do this in many places throughout my code.  Is there any way I can do this <em>without</em> casting to <code>int</code> each time I want to print?</p>