1

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!

jdie8274j
  • 155
  • 1
  • 10
  • You can't. Use `int` and either the boundaries yourself or better, if the API is decent it will check itself and throw an exception (e.g. IllegalArgumentException) if the argument is out of range. – m0skit0 Jan 25 '16 at 17:07

1 Answers1

2

You just use a normal int in your program to store the port. When you want to send the int on the wire as a 16-bit value you simply cast it to a short. This just discards the high-order 16-bits (which you weren't using anyway) and the low-order 16-bits are are left unchanged. Example:

public byte[] encode() {
    final int MESSAGE_SIZE = 10;
    int portValue = 54321;
    Bytebuffer buffer = ByteBuffer.allocate(MESSAGE_SIZE);
    buffer.putInt(someInt);
    buffer.putShort((short) portValue);
    buffer.putInt(someOtherInt); 
    return buffer.array();
}

From Narrowing Primitive Conversions:

A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T.

President James K. Polk
  • 40,516
  • 21
  • 95
  • 125