struct.unpack_from in Java
I've got the following instruction in Python I'd like to understand and translate in Java
values = struct.unpack_from('>%dL' % 96, input_content, 0)
What does >%dL mean? I've checked the doc from python http://docs.python.org/library/struct.html but nothing about the percentage. Shall I consider every returned value as a byte in Java and cast开发者_高级运维 it to either double or long ?
Thanks for your help.
The %d
is a Python string formatter similar to that found in C
. What it says is put the thing that comes after the closing quote in place of the formatter, in this case 96
in place of %d
. The %d
specifies a signed integer decimal.
The '>%dL'%96
is an instruction to struct.unpack
to say that the thing it needs to unpack is a big endian unsigned long with an unsigned integer decimal inside it. Before the '>%dL'
is passed to unpack
however the string formatter is resolved and '>%dL'
becomes '>96L'
. Have a look at the format strings section in `struct.unpack docs
http://docs.python.org/library/stdtypes.html#string-formatting
http://docs.python.org/library/struct.html?highlight=struct.unpack#format-strings
The Python interactive prompt is your friend:
>>> '>%dL' % 96
'>96L'
>>>
So,
values = struct.unpack_from('>%dL' % 96, input_content, 0)
is equivalent to
values = struct.unpack_from('>96L', input_content, 0)
and the struct
docs should tell you that '>96L' means 96 bigendian unsigned 32-bit integers.
I can't imagine why the original author wrote it in such an obfuscatory manner. It is necessary to use a technique like that to build a format if the number of items is variable, but not when it's a known constant.
If I would write the same thing in Java it could be something like:
DataInputStream inputcontent = new DataInputStream(in);
long[] values = new long[96];
for (int i = 0; i < 96; i++)
values[i] = inputcontent.readLong();
with the difference that the python code is using bytes that have been already loaded.
Many thanks to John Machin and Matti for their explanation.
精彩评论