Is there a faster way to convert data to bytes and then back to the original form?

I use a queue service that only accepts messages as a byte, so I need to quickly convert my data to a format, and then return it to its original state when I get work from the queue. My data format is INT, DOUBLE and INT [], and this is how I did it first

//to convert to string
String[] message = { Integer.toString(number), String.valueOf(double), Arrays.toString(my_list) };
message.asString;
//to convert back
String message_without_brackets = message.replace("[", "" ).replace("]", "");
String[] temp_message = message_without_brackets.split(","); 

int interger = Integer.valueOf(temp_message[0]);
double double = Double.valueOf(temp_message[1]);
int[] my_list = new int[temp_message.length-2]; //-2 because the first two entries are other data

for (int i = 2; i < temp_message.length; i++) {
    my_list[i-2] = Integer.parseInt(temp_message[i].replace(" ",""));
}

This is very ugly, and it annoyed me that after a few weeks (or one night of heavy drinking) I probably won’t be able to figure it out quickly. Performance wise code was not so bad, I think it replacewas the hardest part of the code (if I remember that it was like 15% of the total execution).

Gson, , 40% ( Gson ):

    Gson gson = new Gson();
    int[] sub = { 0, 59, 16 };
    Object[] values = { 0, 43.0, sub };
    String output = gson.toJson(values); // => [0, 43.0,[0,59,16]]

    Object[] deserialized = gson.fromJson(output, Object[].class);
    System.out.println(deserialized[0]);
    System.out.println(deserialized[1]);
    System.out.println(deserialized[2]);

, , ? question, , - , ( , )? - Gson, Json, , , , ?

EDIT: , , , getBytes(), - , , getBytes() ?

+3
2

DataOutputStream,

ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);

int i = 0;
double d = 43.0;
int[] sub = { 0, 59, 16 };

dos.writeInt(i);
dos.writeDouble(d);
dos.write(sub.length);
for (int j : sub)
    dos.writeInt(j);

byte[] bytes = baos.toByteArray();

, ByteBuffers ByteBuffers . .

+3

All Articles