如何解码包含无效字节的字节对象,Python3

How to decode bytes object that contains invalid bytes, Python3

在python2中,我可以整天生成这些以字符串格式表示的十六进制字节 '\x00\xaa\xff'

>>>’00'.decode('hex') + 'aa'.decode('hex') + 'ff'.decode('hex')
>>>'\x00\xaa\xff'

同样,我可以在 python3

>>> bytes.fromhex(’00’) + bytes.fromhex(‘aa’) + bytes.fromhex(‘ff’)
>>>b'\x00\xaa\xff'

根据py2->py3变化here

Python 3.0 uses the concepts of text and (binary) data instead of Unicode strings and 8-bit strings. All text is Unicode; however encoded Unicode is represented as binary data.

因此 Py2 版本的输出是字符串,而 Py3 版本的是字节类型的二进制数据

但我真的需要一个字符串版本!

根据上述文档:

As the str and bytes types cannot be mixed, you must always explicitly convert between them. Use str.encode() to go from str to bytes, and bytes.decode() to go from bytes to str. You can also use bytes(s, encoding=...) and str(b, encoding=...), respectively.

好的,现在我必须解码这个字节类型的二进制数据……

>>> b'\x00\xaa\xff'.decode()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xaa in position 1: invalid start byte

糟糕!我不关心这里的 UTF-8 编码。

我能得到一个虚拟直通编解码器吗?

PS

为什么我需要 '\x00\xaa\xff' 而不是 b'\x00\xaa\xff'

因为我将这个字符串传递给

一个用纯python

写的crc function
crc16pure.crc16xmodem('\x00\xaa\xff')

此函数期望遍历由字节组成的字符串。 如果我给出函数 b'\x00\xaa\xff' 那么这只是一个无法迭代的数字。

问题:我可以得到一个虚拟 pass-through 编解码器吗?

答案:是的,使用iso-8859-1

在python3中,以下不工作

b'\x00\xaa\xff'.decode()

默认编解码器'utf-8'无法解码字节0xaa

只要您不关心字符集(例如,当您 print() 时看到的是什么字符)并且只需要一个 8 位字符的字符串,就像您在 [=28= 中得到的那样],然后使用8位编解码器iso-8859-1

b'\x00\xaa\xff'.decode('iso-8859-1')