title: Defined behavior, passing character to printf("%02X"
body: <p>I recently came across <a href="https://stackoverflow.com/questions/6063039/mac-address-printing">this question</a>, where the OP was having issues printing the hexadecimal value of a variable.  I believe the problem can be summed by the <a href="http://www.ideone.com/MOega" rel="nofollow noreferrer">following code</a>:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  
  int main() {
      char signedChar = 0xf0;
  
      printf("Signed\n”);
      printf(“Raw: %02X\n”, signedChar);
      printf(“Masked: %02X\n”, signedChar &amp;0xff);
      printf(“Cast: %02X\n", (unsigned char)signedChar);
  
      return 0;
  }
  </code></pre>
  
  <p>This gives the following output:</p>
  
  <pre><code>Signed
  Raw: FFFFFFF0
  Masked: F0
  Cast: F0
  </code></pre>
  
  <p>The format string used for each of the prints is <code>%02X</code>, which I’ve always interpreted as ‘print the supplied <code>int</code> as a hexadecimal value with at least two digits’.</p>
  
  <p>The first case passes the signedCharacter as a parameter and prints out the wrong value (because the other three bytes of the <code>int</code> have all of their bits set).</p>
  
  <p>The second case gets around this problem, by applying a bit mask (<code>0xFF</code>) against the value to remove all but the least significant byte, where the <code>char</code> is stored.  Should this work?  Surely: <code>signedChar == signedChar &amp; 0xFF</code>?</p>
  
  <p>The third case gets around the problem by casting the character to an <code>unsigned char</code> (which seems to clear the top three bytes?).</p>
  
  <p>For each of the three cases above, can anybody tell me if the behavior defined? How/Where?</p>