[英]How to decode base64 to single bytes?
In the following code:在以下代码中:
import base64
base64.decodebytes('DBCCOAABAMA='.encode('ascii'))
the result is结果是
b'\x0c\x10\x828\x00\x01\x00\xc0'
The third byte is \\x828
which does not fit into a single byte and lead into a problem for my script.第三个字节是
\\x828
,它不适合单个字节并导致我的脚本出现问题。 I do not want to decode it as anything else than ASCII
.我不想将它解码为
ASCII
以外的任何东西。
Is there anything wrong with the initial base64 encoder?初始base64编码器有什么问题吗? Why does this problem happen and how can I fix it?
为什么会发生这个问题,我该如何解决?
Update:更新:
The problem I face is the code我面临的问题是代码
base64.decodebytes('DBCCOAABAMA='.encode('ascii')).decode('ascii')
leads to an error导致错误
UnicodeDecodeError: 'ascii' codec can't decode byte 0x82 in position 2: ordinal not in range(128)
Some bytes, if they fall in the printable character range, don't get printed as hex escapes.某些字节,如果它们落在可打印字符范围内,则不会以十六进制转义形式打印。 This little bit of code shows you what's really happening:
这段代码向您展示了真正发生的事情:
>>> for b in base64.decodebytes('DBCCOAABAMA='.encode('ascii')):
print(hex(b), chr(b))
0xc
0x10
0x82 ‚
0x38 8
0x0
0x1
0x0
0xc0 À
PS I don't understand why encode
didn't throw an error, some of those bytes are outside of the ASCII range. PS 我不明白为什么
encode
没有抛出错误,其中一些字节超出了 ASCII 范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.