假设我有一个字符串:你好!
我必须做这一切:
- 将字符串转换为字节数组
- 发送字节数组
- 将其转换回字符串(供以后使用)
这是我的代码...
//Sender
String send = "Hello!";
byte[] data = send.getBytes();
DatagramPacket packetOut = new DatagramPacket(data, data.length); //send blah blah
//Receiver
//blah blah receive it
String receive = new String(packetIn.getData()); //convert it back
对整数数组执行此操作的快速而优雅的方法是什么?
最佳答案
对于 int[],您可以使用 ObjectOutputStream 进行序列化,但更快的方法可能是使用 ByteBuffer。
public static byte[] intsToBytes(int[] ints) {
ByteBuffer bb = ByteBuffer.allocate(ints.length * 4);
IntBuffer ib = bb.asIntBuffer();
for (int i : ints) ib.put(i);
return bb.array();
}
public static int[] bytesToInts(byte[] bytes) {
int[] ints = new int[bytes.length / 4];
ByteBuffer.wrap(bytes).asIntBuffer().get(ints);
return ints;
}
关于java - 通过数据报包发送数组的最佳方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12954424/