如何使用 Java ByteBuffer 处理负整数

How to handle negative int with Java ByteBuffer

我有一个 Android 应用程序,它使用 ByteBuffer 将一个整数数组(转换为字符串)发送到我的服务器,它是用 Ruby 编写的。服务器获取字符串并将其解包。我构建 ByteBuffer 的代码如下所示:

ByteBuffer bytes = ByteBuffer.allocate(16);
bytes.order(ByteOrder.LITTLE_ENDIAN);

bytes.putInt(int1);
bytes.putInt(int2);
bytes.putInt(int3);
bytes.putInt(int4);

String byteString = new String(bytes.array());

当整数都是正值时,这很有效。当它有一个负整数时,事情就会出错。例如,在 iOS 中,当我提交一个像 [1,1,-1,0] 这样的整数数组时,服务器上的字节串是:

"\x01\x00\x00\x00\x01\x00\x00\x00\xFF\xFF\xFF\xFF\x00\x00\x00\x00"

正确解压为 [1,1,-1,0]。

在 Android 中,但是,当我尝试提交相同的 [1,1,-1,0] 数组时,我的字符串是:

"\x01\x00\x00\x00\x01\x00\x00\x00\xEF\xBF\xBD\xEF\xBF\xBD\xEF\xBF\xBD\xEF\xBF\xBD\x00\x00\x00\x00"

解压到 [1, 1, -272777233, -1074807361]。

如果我将负整数转换为无符号整数:

byte intByte = (byte) -1;
int unsignedInt = intByte & 0xff;

我得到以下信息:

"\x01\x00\x00\x00\x01\x00\x00\x00\xEF\xBF\xBD\x00\x00\x00\x00\x00\x00\x00"

解压到 [1, 1, 12435439, 0]。我希望有人能帮我弄清楚如何正确处理这个问题,以便我可以正确发送负值。

你的问题在这里:

String byteString = new String(bytes.array());

你为什么要这么做?您想发送字节流,那么为什么要将其转换为 char 的流?

如果要发送字节,请发送字节。使用 OutputStream,而不是 Writer;使用 InputStream,而不是 Reader。整数是 "negative" 或 "positive" 并不重要。