A port range goes from 0 to 65536 as it is stored as a 16-bit unsigned integer.
In Java, a short which is 16-bit only goes up to 32,767. An integer would be fine, but the API expects an unsigned integer, so it must fit within 16 bits.
My first attempt was as follows:
public byte[] encode() {
final int MESSAGE_SIZE = 10;
Bytebuffer buffer = ByteBuffer.allocate(MESSAGE_SIZE);
buffer.putInt(someInt);
buffer.putShort(portValue);
buffer.putInt(someOtherInt);
return buffer.array();
}
But clearly, I cannot represent a port above 32,767 if I simply use a short.
My question is, how can I put a value that can be up to 65536 as a short into the buffer so that the receiving API can interpret it within 16 bits?
Thank you!