gpt4 book ai didi

java - 如何按照 C 和 C++ 的字节顺序将类转换为字节数组?

转载 作者:行者123 更新时间:2023-11-30 15:52:47 24 4
gpt4 key购买 nike

我正在创建一个字节数组的类对象,请参阅 here ,并将该数组传递给 DatagramPacket 以通过 UDP 通信方式发送到目的地。在目标端,C 应用程序正在运行,我正在获取有线字符。我确信这与字节顺序有关。因为我能够在接收数据包时将 C 的结构转换为类,但反之亦然。以下是 sudo - 代码:

// recieving part

DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet)
UdpPacket udp = new UdpPacket(buffer);

class UdpPacket implements Serializable
{
int a;
byte []message = new byte[10];

public UdpPacket(byte[] data)
{
ByteBuffer bb = ByteBuffer.wrap(data);
bb.order(ByteOrder.nativeOrder());
a = bb.getInt();
bb.get(message);
}

}

// sending ..

按照上述链接将 UdpPacket 对象转换为字节数组,但在目标处始终存在垃圾值

DatagramSocket clientSocket = new DatagramSocket();

byte [] respoBytes = ObjectSerializer.serializeObject(udpPacket);

ByteBuffer bb = ByteBuffer.wrap(respoBytes);


byte []test = new byte[1116];
bb.order(ByteOrder.nativeOrder()); // tried all the orders here
bb.get(test);
DatagramPacket sendPacket = new DatagramPacket(test,test.length,client, Integer.parseInt(TxtFdPort.getText().toString()));
clientSocket.send(sendPacket)

;

最佳答案

最明显的问题是忽略读取数据的长度。

DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);

ByteBuffer bb = ByteBuffer.wrap(packet.getData(), 0, packet.getLength());
// you need to know the endianess, not hope it's the same.
bb.order(ByteOrder.LITTLE_ENDIAN);
int a = bb.getInt(); // asuming there is at least 4 bytes.
byte[] message = new byte[bb.remaining()];
bb.get(message);

对于发送,我会这样做。

int port = Integer.parseInt(TxtFdPort.getText().toString());
byte [] respoBytes = ObjectSerializer.serializeObject(udpPacket);
DatagramPacket sendPacket = new DatagramPacket(respoBytes, respoBytes.length, client, port);
clientSocket.send(sendPacket);

关于java - 如何按照 C 和 C++ 的字节顺序将类转换为字节数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14138535/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com