Say I had a String: Hello!
I have to do all this:
This is my code...
//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
What's a quick and elegant way to do this for an array of integers?
For an int[] you can serialize using ObjectOutputStream but a faster way might be to use a 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;
}