title: The %x format specifier with an unsigned char in C
body: <p>I ran across the following example program and I don't exactly understand it's output:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  
  int main( void ) {
  
      unsigned char i, m =0xFF, n=0x1;
  
      for ( i = 0; i != 8; i++,n+=n, m/=2 )
          printf("%5x %5x %5x %5x %5x %5x\n", n,m,n&amp;m,n|m,n^m,~n);
  
      return 0;
  }
  </code></pre>
  
  <p>It prints out:</p>
  
  <pre><code>    1    ff     1    ff    fe fffffffe
      2    7f     2    7f    7d fffffffd
      4    3f     4    3f    3b fffffffb
      8    1f     8    1f    17 fffffff7
     10     f     0    1f    1f ffffffef
     20     7     0    27    27 ffffffdf
     40     3     0    43    43 ffffffbf
     80     1     0    81    81 ffffff7f
  </code></pre>
  
  <p>The problem is that last column.  Since it's unsigned char I would expect it to print out just 2 places in every column.  <code>~n</code> produces an unsigned char as it's result, but it seems like it's being cast to a signed 32 bit value and sign extended by the <code>%5x</code> specifier.</p>
  
  <p>How is that possible, what's going on here?</p>