3

我有一个混合了字符和字节的列表,如下所示:

myData = ['a', '\x65', 'B', '\x66\x69', 'C']

我想将此列表转换为字节数组,因此:

myByteArray = ['\x61' , '\x65', '\x42', '\x66', '\x69', '\x43']

到目前为止,我尝试的是在 myData 上进行简单显示——

myData = ['a', '\x65', 'B', '\x66\x69', 'C']
print " ".join(hex(ord(n)) for n in myData)

由于数组中有一个元素恰好是两个字节,因此会引发此错误:

Traceback (most recent call last):
  File "./test.py", line 3, in <module>
    print " ".join(hex(ord(n)) for n in myData)
  File "./test.py", line 3, in <genexpr>
    print " ".join(hex(ord(n)) for n in myData)
TypeError: ord() expected a character, but string of length 2 found

如何将原始列表 myData 转换为字节数组 myByteArray?

4

2 回答 2

1

您可以将它们全部合并并再次拆分以获取单个字符,例如:

   output_list = [hex(ord(c)) for c in ''.join(myData)]

试一试,

>>> myData = ['a', '\x65', 'B', '\x66\x69', 'C']
>>> [hex(ord(c)) for c in ''.join(myData)]
['0x61', '0x65', '0x42', '0x66', '0x69', '0x43']
于 2013-10-08T18:08:40.613 回答
1

如果你真的想要一个list可变字节而不是一个不可变的单字符字符串,你可以这样做:

myData = ['a', '\x65', 'B', '\x66\x69', 'C', '\xff']

myByteArray = bytearray(''.join(myData))

print " ".join(hex(byte) for byte in myByteArray)
# 0x61 0x65 0x42 0x66 0x69 0x43 0xff

如果一个list字符的字符串是可以的,那么您只需要:

myByteArray = list(''.join(myData))
于 2013-10-08T18:50:48.957 回答