4
\$\begingroup\$

Given the test code:

import struct
buf = bytearray(b'\xef\xf8\t\xf2')
number = struct.unpack("<I", buf)[0]

How do I cleanly make it work both under Python 2.6 and Python 3.3? The problem is that struct.unpack in Python 2.6 seems to expect a str object (not unicode), so the only way I managed to come up with in order to get it working on both versions is:

buf_raw = bytearray(b'\xef\xf8\t\xf2')
buf_decoded = buf_raw.decode('latin1')
buf_encoded = buf_decoded.encode('latin1')
number = struct.unpack("<I", buf_encoded)[0]

...though I'm abusing the fact that latin1 translates every 0-255 ASCII character to itself. What's the better way?

\$\endgroup\$

1 Answer 1

6
\$\begingroup\$

Why not just call bytes?

number = struct.unpack('<I', bytes(buf))[0]

In Python 2.6:

Python 2.6.8 (unknown, Aug 13 2012, 22:19:05) 
...
>>> import struct
>>> struct.unpack('<I', bytes(bytearray(b'ABCD')))
(1145258561,)

In Python 3.3:

Python 3.3.2 (default, May 21 2013, 11:50:47) 
...
>>> import struct
>>> struct.unpack('<I', bytes(bytearray(b'ABCD')))
(1145258561,)
\$\endgroup\$
1
  • \$\begingroup\$ How to handle it while double back slash issue.. For example b'\\xef\\xf8\\t\\xf2'.. \$\endgroup\$ Dec 26, 2018 at 11:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.