Python 将 Base64 字符串解码为字节数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39209872/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Decode Base64 string to byte array
提问by Federico
I would create a python script that decode a Base64 string to an array of byte (or array of Hex values).
我将创建一个 python 脚本,将 Base64 字符串解码为字节数组(或十六进制值数组)。
The embedded side of my project is a micro controller that creates a base64 string starting from raw byte. The string contains some no-printable characters (for this reason I choose base64 encoding).
我的项目的嵌入式端是一个微控制器,它从原始字节开始创建一个 base64 字符串。该字符串包含一些不可打印的字符(因此我选择 base64 编码)。
On the Pc side I need to decode the the base64 string and recover the original raw bytes.
在 PC 端,我需要解码 base64 字符串并恢复原始原始字节。
My script uses python 2.7 and the base64 library:
我的脚本使用 python 2.7 和 base64 库:
base64Packet = raw_input('Base64 stream:')
packet = base64.b64decode(base64Packet )
sys.stdout.write("Decoded packet: %s"%packet)
The resulting string is a characters string that contains some not printable char.
结果字符串是一个字符串,其中包含一些不可打印的字符。
Is there a way to decode base64 string to byte (or hex) values?
有没有办法将 base64 字符串解码为字节(或十六进制)值?
Thanks in advance!
提前致谢!
采纳答案by janbrohl
You can use bytearrayfor exactly this. Possibly the binasciimodule and structcan be helpful, too.
您可以为此使用bytearray。可能binascii模块和结构也有帮助。
import binascii
import struct
binstr=b"thisisunreadablebytes"
encoded=binascii.b2a_base64(binstr)
print encoded
print binascii.a2b_base64(encoded)
ba=bytearray(binstr)
print list(ba)
print binascii.b2a_hex(binstr)
print struct.unpack("21B",binstr)