在Java中将大于127的short写入ByteBuffer



我有一个应用程序,我正在尝试使用TSLv5发送UDP消息。协议有点复杂,但要做到这一点,我需要将16位值写为小端序,然后通过UDP发送。

这是我的代码:

buffer.order(ByteOrder.LITTLE_ENDIAN);
buffer.putShort(SCREEN_POS, screen);
buffer.putShort(INDEX_POS, index);
ByteBuffer text = ByteBuffer.wrap(value.getBytes());
short textLength = (short) value.getBytes().length;
buffer.putShort(LENGTH_POS, textLength);
ByteBuffer combined = ByteBufferUtils.concat(buffer, text);
short control = 0x00;
control |= rhTally << 0;
control |= textTally << 2;
control |= lhTally << 4;
control |= brightness << 6;
combined.putShort(CONTROL_POS, control);
short msgLength = (short) (combined.array().length - 2);
combined.putShort(PBC_POS, msgLength);
return new DatagramPacket(combined.array(), combined.array().length, ip, 9000);

这基本上是有效的,但问题是当我的值大于127时。

例如,我的索引是148,当一切都说了算,我的控制就变成了193。当我将这些值写入ByteBuffer时,它们分别变为-108-63

我知道为什么会发生这种情况,ByteBuffer是一个字节数组,字节不能大于127。我不知道的是我如何才能做到这一点?如果我发送签名值,协议就不起作用,它必须是确切的数字。

我可以确保在short的两个字节中正确读取有符号的java字节。我简化了代码,以线性方式一个接一个地编写字段,前面有消息字段。还只使用了一个ByteBuffer。

(也许有一些小错误,比如偏移错误。(

此外,我以UTF-8格式发送文本字节。您使用了隐式平台编码,这可能在每台计算机上有所不同。

byte[] text = value.getBytes(StandardCharsets.UTF_8);
int textLength = text.length;
int length = 2 + 2 + 2 + 2 + 2 + textLength;
ByteBuffer buffer = ByteBuffer.allocate(length)
.order(ByteOrder.LITTLE_ENDIAN);
short control = 0x00;
control |= rhTally << 0;
control |= textTally << 2;
control |= lhTally << 4;
control |= brightness << 6;
buffer.putShort(/*CONTROL_POS,*/ control);
short msgLength = (short) (length - 2);
buffer.putShort(/*PBC_POS,*/ msgLength);
buffer.putShort(/*SCREEN_POS,*/ screen);
buffer.putShort(/*INDEX_POS,*/ index);
buffer.putShort(/*LENGTH_POS,*/ (short)textLength);
buffer.put(text, 0, textLength);
return new DatagramPacket(buffer.array(), length, ip, 9000);

最新更新