端口范围从 0 到 65536,因为它存储为 16 位无符号整数。
在 Java 中,16 位的 short 最多只能达到 32,767。一个整数就可以了,但 API 需要一个无符号整数,因此它必须在 16 位以内。
我的第一次尝试如下:
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();
}
但很明显,如果我只是使用一个 short,我不能代表 32,767 以上的端口。
我的问题是,如何将一个最大为 65536 的值作为一个 short 放入缓冲区,以便接收 API 可以在 16 位以内解释它?
谢谢!
您只需在程序中使用普通的int
来存储端口。当您想将 int 作为 16 位值发送到网络时,您只需将其转换为 short。这只是丢弃了高位 16 位(无论如何您都没有使用),而低位 16 位保持不变。示例:
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();
}
来自 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.