title: How can I safely use a Java byte as an unsigned char?
body: <p>I am porting some C code that uses a lot of bit manipulation into Java. The C code operates under the assumption that int is 32 bits wide and char is 8 bits wide. There are assertions in it that check whether those assumptions are valid. </p>
  
  <p>I have already come to terms with the fact that I'll have to use <code>long</code> in place of <code>unsigned int</code>. But can I safely use <code>byte</code> as a replacement for <code>unsigned char</code>? </p>
  
  <p>They merely represent bytes, but I have already run into this bizarre incident: (<code>data</code> is an <code>unsigned char *</code> in C and a <code>byte[]</code> in Java):</p>
  
  <pre><code>/* C */
  uInt32 c = (data[0] &lt;&lt; 24) | (data[1] &lt;&lt; 16) | (data[2] &lt;&lt; 8) | data[3];
  
  /* Java */
  long a = ((data[0] &lt;&lt; 24) | (data[1] &lt;&lt; 16) | (data[2] &lt;&lt; 8) | data[3]) &amp; 0xffffffff;
  long b = ((data[0] &amp; 0xff) &lt;&lt; 24) | ((data[1] &amp; 0xff) &lt;&lt; 16) |
            ((data[2] &amp; 0xff) &lt;&lt; 8) | (data[3] &amp; 0xff) &amp; 0xffffffff;
  </code></pre>
  
  <p>You would think a left shift operation is safe. But due strange unary promotion rules in Java, <code>a</code> and <code>b</code> are not going to be the same if some of the bytes in <code>data</code> are "negative" (<code>b</code> gives the correct result).</p>
  
  <p>What other "gotchas" should I be aware of? I really don't want to use <code>short</code> here.</p>