我正在尝试创建一个可靠的UDP系统,需要将byte[]转换为int类型,然后再转回去(使用JCreator 5.0 LE)。
DatagramPacket要求数据以byte[]形式提供,因此我需要将int信息转换为byte[],以便可以发送它:
byte[] data = new byte[48];
System.arraycopy(task.getProtocol().byteValue(), 0, data, 0, task.getProtocol().byteValue().length);
System.arraycopy(task.getMessage().byteValue(), 0, data, 4, task.getMessage().byteValue().length);
System.arraycopy(task.getSequence().byteValue(), 0, data, 8, task.getSequence().byteValue().length);
System.arraycopy(task.getAcknowledge().byteValue(), 0, data, 12, task.getAcknowledge().byteValue().length);
for (int i = task.getAcknowledge(); i >= 0 && i > task.getAcknowledge() - 33; i--) {
for (Packet j: tasks) {
if (j.getSequence() == i) {
data[i] = 1;
break;
}
}
}
out = new DatagramPacket(data, data.length, ds.getInetAddress(), portNum);
ds.send(out);
协议是协议ID
消息是被发送的“信息”
序列是数据包的序列号;第一个发送的数据包的序列号为0,下一个为1,以此类推
确认是返回已发送的数据包的确认
下一部分是32个其他确认。 为了节省内存,它们被压缩成每个字节而不是4个字节(int)
现在,当我接收到数据包时,我需要将其解包。 首先,我需要检查前4个字节(协议),以确定是否要忽略数据包,但我不知道如何将字节数组转换为int。