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 int to short while calling shortToBytes method. This works fine till checksum value is less than 32767 thereafter i am getting negative values.
Thing is java does not have unsigned primitives, so i am not able to send values greater than max value of signed short allowed.
How can i do this, converting int to short and send over the network without worrying about truncation and signed & unsigned int.
Also on both the side i have java program running.
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();
}
You are still getting the same bit value as the server. So, to see the right numerical value replace the
ByteBuffer.wrap(baValue).getShort()to aByteBuffer.wrap(baValue).getInt(). This should give you the same numerical value as the server.