简体   繁体   中英

Decode Base64 string to byte array

I would create a python script that decode a Base64 string to an array of byte (or array of Hex values).

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).

On the Pc side I need to decode the the base64 string and recover the original raw bytes.

My script uses python 2.7 and the base64 library:

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?

Thanks in advance!

You can use bytearray for exactly this. Possibly the binascii module and struct can be helpful, too.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM