0

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
syker
  • 10,912
  • 16
  • 56
  • 68
  • 1
    I don't know any Perl. If I knew what that code was doing I might be able to help. – takendarkk Oct 10 '14 at 21:28
  • I inspected the API for DatatypeConverter and I didn't see how I could pack my list into unsigned longs (32-bit) in "network" (big-endian) order. – syker Oct 10 '14 at 21:31
  • @skyer you could use java's nio outputs using `ByteBuffer.allocate(size).order(endianness).asIntBuffer()` to setup an IntBuffer with endian the way you need it – Joakim Erdfelt Oct 10 '14 at 22:20

1 Answers1

0

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();
David Conrad
  • 15,432
  • 2
  • 42
  • 54
  • 1) I'm curious why stream.writeInt() worked and not stream.wrtiteLong(). Is that because a Java Int is interpreted as an unsigned long? If so, what is a Java Long interpreted as? 2) baos.toString() is what I needed, thanks. – syker Oct 10 '14 at 22:07
  • A `long` in Java is 64 bits, an `int` is 32 bits. Signed vs. unsigned doesn't matter when you're just writing them, since it doesn't change the representation. `baos.toString()` uses whatever the default platform encoding is. You might want to explicitly specify an encoding e.g., `baos.toString("UTF-8")`. – David Conrad Oct 10 '14 at 22:11
  • Does stream.write() write 1 byte or 4 bytes? According to the Javadoc [1], it appears to be 1 byte. [1] http://docs.oracle.com/javase/7/docs/api/java/io/DataOutputStream.html#write(int) – syker Oct 15 '14 at 19:15
  • Yes, that's right, 1 byte. Doesn't `"C"` in Perl `pack` write one byte? As I said, my Perl is very rusty. – David Conrad Oct 15 '14 at 20:34
  • `man perlfunc`, under `pack`, for `C`, says: "An unsigned char (octet) value." – David Conrad Oct 15 '14 at 20:36