Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The Perl format <code>"nNcc"</code> is equivalent to the Python format <code>"!HLbb"</code>. There is no direct equivalent in Python for Perl's <code>"H*"</code>.</p> <p>There are two problems.</p> <ul> <li>Python's <code>struct.unpack</code> does not accept the wildcard character, <code>*</code></li> <li>Python's <code>struct.unpack</code> does not "hexlify" data strings</li> </ul> <p>The first problem can be worked-around using a helper function like <code>unpack</code>.</p> <p>The second problem can be solved using <code>binascii.hexlify</code>:</p> <pre class="lang-py prettyprint-override"><code>import struct import binascii def unpack(fmt, data): """ Return struct.unpack(fmt, data) with the optional single * in fmt replaced with the appropriate number, given the length of data. """ # http://stackoverflow.com/a/7867892/190597 try: return struct.unpack(fmt, data) except struct.error: flen = struct.calcsize(fmt.replace('*', '')) alen = len(data) idx = fmt.find('*') before_char = fmt[idx-1] n = (alen-flen)//struct.calcsize(before_char)+1 fmt = ''.join((fmt[:idx-1], str(n), before_char, fmt[idx+1:])) return struct.unpack(fmt, data) data = open('data').read() x = list(unpack("!HLbbs*", data)) # x[-1].encode('hex') works in Python 2, but not in Python 3 x[-1] = binascii.hexlify(x[-1]) print(x) </code></pre> <p>When tested on data produced by this Perl script:</p> <pre><code>$line = pack("nNccH*", 1, 2, 10, 4, '1fba'); print "$line"; </code></pre> <p>The Python script yields</p> <pre><code>[1, 2, 10, 4, '1fba'] </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload