Given the test code:import structbuf = 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?
struct.unpack on a bytearray that works under Python 2.6.6, 2.7 and 3.3?
python;python 3.x
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,)