Есть строка вида ‘\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00’
Можно ли ее певратить в список вида (1,2,3,4,5,0) без использования цикла?
s ='\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00' struct.unpack('i'*(len(s)/4),s)
By default, C types are represented in the machine’s native format and byte order, and properly aligned by skipping pad bytes if necessary (according to the rules used by the C compiler).Надо вручную указывать порядок байтов.
struct.unpack('<%si' % (len(s)/4),s)
>>> s = '\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00' >>> s.encode('latin1') b'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00' >>> s.encode('latin1')[0] 1 >>>
>>> s = '\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00' >>> bytearray(s) bytearray(b'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00') >>> bytearray(s)[0] 1 >>>
>>> type(bytearray(b'abc')[0]) <type 'int'> >>>
>>> s = '\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00' >>> bytearray(s) bytearray(b'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00') >>> bytearray(s)[0] 1 >>> bytearray(s)[1] 0 # а должно быть 2
>>> array('L',s) array('L', [1L, 2L, 3L, 4L, 5L, 0L])
>>> s = '\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00' >>> bytearray(s[::4]) bytearray(b'\x01\x02\x03\x04\x05\x00') >>> bytearray(s[::4])[0] 1 >>> bytearray(s[::4])[1] 2 >>>
>>> s = '\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00' >>> s.decode('utf-32le') u'\x01\x02\x03\x04\x05\x00' >>> map(ord, s.decode('utf-32le')) [1, 2, 3, 4, 5, 0] >>>
py.user.nextНу это, извини меня, быдлокод нижайшего пошиба.>>> s = '\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00' >>> bytearray(s[::4]) bytearray(b'\x01\x02\x03\x04\x05\x00') >>> bytearray(s[::4])[0] 1 >>> bytearray(s[::4])[1] 2 >>>