title: java converting int to short
body: <p>I am calculating 16 bit checksum on my data which i need to send to server where it has to recalculate and match with the provided checksum. Checksum value that i am getting is in int but i have only 2 bytes for sending the value.So i am casting <code>int</code> to <code>short</code> while calling <code>shortToBytes</code> method. This works fine till checksum value is less than 32767 thereafter i am getting negative values.</p>
  
  <p>Thing is java does not have unsigned primitives, so i am not able to send values greater than max value of signed <code>short</code> allowed.</p>
  
  <p>How can i do this, converting int to short and send over the network without worrying about truncation and signed &amp; unsigned int.</p>
  
  <p>Also on both the side i have java program running.</p>
  
  <pre><code>   private byte[] shortToBytes(short sh) {
          byte[] baValue = new byte[2];
          ByteBuffer buf = ByteBuffer.wrap(baValue);
          return buf.putShort(sh).array();
      }
  
      private short bytesToShort(byte[] buf, int offset) {
          byte[] baValue = new byte[2];
          System.arraycopy(buf, offset, baValue, 0, 2);
          return ByteBuffer.wrap(baValue).getShort();
      }
  </code></pre>