patternpythonMinor
struct.unpack on a bytearray that works under Python 2.6.6, 2.7 and 3.3?
Viewed 0 times
bytearraystructworksunderthatunpackpythonand
Problem
Given the test code:
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:
...though I'm abusing the fact that
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?Solution
Why not just call
In Python 2.6:
In Python 3.3:
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,)Code Snippets
number = struct.unpack('<I', bytes(buf))[0]Python 2.6.8 (unknown, Aug 13 2012, 22:19:05)
...
>>> import struct
>>> struct.unpack('<I', bytes(bytearray(b'ABCD')))
(1145258561,)Python 3.3.2 (default, May 21 2013, 11:50:47)
...
>>> import struct
>>> struct.unpack('<I', bytes(bytearray(b'ABCD')))
(1145258561,)Context
StackExchange Code Review Q#37959, answer score: 6
Revisions (0)
No revisions yet.