title: getting the bottom 16 bits of a Java int as a signed 16-bit value
body: <p>Hmmm. Consider this program, whose goal is to figure out the best way to get the bottom 16 bits of an integer, as a signed integer.</p>
  
  <pre><code>public class SignExtend16 {
      public static int get16Bits(int x)
      { 
          return (x &amp; 0xffff) - ((x &amp; 0x8000) &lt;&lt; 1);
      }
  
      public static int get16Bits0(int x)
      { 
          return (int)(short)(x);
      }    
  
      public static void main(String[] args)
      {
          for (String s : args)
          {
              int x = Integer.parseInt(s);
              System.out.printf("%08x =&gt; %08x, %08x\n",
                 x, get16Bits0(x), get16Bits(x));
          }
      }
  }
  </code></pre>
  
  <p>I was going to use the code in get16Bits0, but I got the warning "Unnecessary cast from short to int" with Eclipse's compiler and it makes me suspicious, thinking the compiler could optimize out my "unnecessary cast". When I run it on my machine using Eclipse's compiler, I get identical results from both functions that behave the way I intended (test arguments: 1 1111 11111 33333 66666 99999 ). Does this mean I can use get16Bits0? (with suitable warnings to future code maintainers) I've always assumed that JRE and compiler behavior are both machine-independent for arithmetic, but this case is testing my faith somewhat.</p>