title: When casting a small integer type to a wider one, is it safe to rely on &ing with a mask to remove the sign?
body: <p>I have code that stores values in the range 0..255 in a Java <code>byte</code> to save space in large data collections (10^9 records spread over a couple hundred arrays).</p>
  
  <p>Without additional measures on recovery, the larger values are interpreted as being negative (because the Java integer types use <a href="http://en.wikipedia.org/wiki/Twos_complement" rel="nofollow noreferrer">two's complement</a> representation).</p>
  
  <p>I got <a href="https://stackoverflow.com/questions/771663/java-why-doesnt-binary-or-work-as-expected-see-code-below/771746#771746">this helpful hint</a> from <a href="https://stackoverflow.com/users/49246/starblue">starblue</a> in response to a related question, and I'm wondering if this technique is safe to rely on:</p>
  
  <pre><code>int iOriginal = 128, iRestore;
  byte bStore = (byte) iOriginal; // reading this value directly would yield -128
  iRestore = 0xff &amp; bStore;
  </code></pre>