java converting int to short
Posted
by changed
on Stack Overflow
See other posts from Stack Overflow
or by changed
Published on 2010-03-21T02:29:30Z
Indexed on
2010/03/21
2:31 UTC
Read the original article
Hit count: 604
Hi
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();
}
© Stack Overflow or respective owner