java converting int to short

changed picture changed · Mar 21, 2010 · Viewed 11.3k times · Source

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();
    }

Answer

Stephen C picture Stephen C · Mar 21, 2010

Firstly, Java int, short and byte types are all signed not unsigned. Secondly, when you cast a Java int to a short, etc you will get silent truncation.

Whether this matters depends on the nature of the checksum algorithm. If it is a simple sum, or a bitwise algorithm there is a good chance that the algorithm is just fine when implemented using Java signed integers. For example, those "negative" 16bit checksums could be correct when interpreted by something expecting unsigned values.

On the other hand, the semantic of multiplication and division are such that signed and unsigned flavors have to be handled separately. (At least, that's what I infer from the unscientific approach of looking at the x86 instruction set ... which has separate instructions for signed versus unsigned multiplication and division.)

EDIT I understand that you are calculating CRC-16. Since that can be computed by shifting and XORing, there should be no concerns about signed versus unsigned numbers during the calculation.

In short, you don't have anything to worry about.