public void routeMessage(byte[] data, int mode) {
logger.debug(mode);
logger.debug(Integer.toBinaryString(mode));
byte[] message = new byte[8];
ByteBuffer byteBuffer = ByteBuffer.allocate(4);
ByteArrayOutputStream baoStream = new ByteArrayOutputStream();
DataOutputStream doStream = new DataOutputStream(baoStream);
try {
doStream.writeInt(mode);
} catch (IOException e) {
logger.debug("Error converting mode from integer to bytes.", e);
return;
}
byte [] bytes = baoStream.toByteArray();
bytes[0] = (byte)((mode >>> 24) & 0x000000ff);
bytes[1] = (byte)((mode >>> 16) & 0x000000ff);
bytes[2] = (byte)((mode >>> 8) & 0x00000ff);
bytes[3] = (byte)(mode & 0x000000ff);
//bytes = byteBuffer.array();
for (byte b : bytes) {
logger.debug(b);
}
for (int i = 0; i < 4; i++) {
//byte tmp = (byte)(mode >> (32 - ((i + 1) * 8)));
message[i] = bytes[i];
logger.debug("mode, " + i + ": " + Integer.toBinaryString(message[i]));
message[i + 4] = data[i];
}
broker.routeMessage(message);
}
我尝试了不同的方法(从注释代码中可以看出)将模式转换为四个字节,以通过套接字将其发送到另一个应用程序。它适用于高达 127 的整数,然后再适用于超过 256 的整数。我相信它与被签名的 Java 类型有关,但似乎并没有让它工作。以下是程序打印的一些示例。
127
1111111
0
0
0
127
mode, 0: 0
mode, 1: 0
mode, 2: 0
mode, 3: 1111111
128
10000000
0
0
0
-128
mode, 0: 0
mode, 1: 0
mode, 2: 0
mode, 3: 11111111111111111111111110000000
211
11010011
0
0
0
-45
mode, 0: 0
mode, 1: 0
mode, 2: 0
mode, 3: 11111111111111111111111111010011
306
100110010
0
0
1
50
mode, 0: 0
mode, 1: 0
mode, 2: 1
mode, 3: 110010
一个字节怎么可能突然存储 32 位?我该如何解决这个问题?