Search code examples
javapack

Equivalent of Perl's 'pack' function in Java


In Perl, I have the following line of code:

pack( "C (N)$cnt", $cnt , @items);

I'm having issues transposing this to Java. How can I do it?


Solution

  • My Perl is pretty rusty but after looking at man perlfunc I think this may be what you want:

    List<Integer> items = ...;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream stream = new DataOutputStream(baos);
    stream.write(items.size());
    for (Integer item : items) {
        stream.writeInt(item);
    }
    stream.flush(); // not sure this is strictly necessary
    byte[] result = baos.toByteArray();